Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

backboneJS 的router执行顺序的BUG #42

Open
mishe opened this issue Dec 3, 2015 · 0 comments
Open

backboneJS 的router执行顺序的BUG #42

mishe opened this issue Dec 3, 2015 · 0 comments

Comments

@mishe
Copy link
Owner

mishe commented Dec 3, 2015

Backbone.Router.extend({
    initialize:function(){
            this.bind('route',function(){
                console.log(1)
            });
        },
        routes:{
            "":"home"
        },
        home:function(){
            console.log(2)
        }
});

以上是backbone的Router简单实例,

页面访问时,先输出2,在输出1,

这个顺序不是很符合页面的执行逻辑;

在来看源码:

route: function(route, name, callback) {

      if (!_.isRegExp(route)) route = this._routeToRegExp(route);

      if (_.isFunction(name)) {

        callback = name;

        name = '';

      }

      if (!callback) callback = this[name];

      var router = this;

      Backbone.history.route(route, function(fragment) {

        var args = router._extractParameters(route, fragment);

        callback && callback.apply(router, args);

        router.trigger.apply(router, ['route:' + name].concat(args));

        router.trigger('route', name, args);

        Backbone.history.trigger('route', router, name, args);

      });

      return this;

    },

页面会触发router事件后,会执行上述代码;

第11行代码会触发router扩展中定于的home函数;

第13行代码会执行我们在initialize函数中绑定的router函数。

参考JQuery的each函数的做法,我们可以适当的修改上述的router函数的执行顺序,并增加条件判断,实现不符合要求的router不执行home函数。

修改后的代码如下

route: function(route, name, callback) {

      if (!_.isRegExp(route)) route = this._routeToRegExp(route);

      if (_.isFunction(name)) {

        callback = name;

        name = '';

      }

      if (!callback) callback = this[name];

      var router = this;

      Backbone.history.route(route, function(fragment) {

        var args = router._extractParameters(route, fragment);

        router.trigger.apply(router, ['route:' + name].concat(args));

        if(router.trigger('route', name, args)!==false) callback && callback.apply(router, args);

        Backbone.history.trigger('route', router, name, args);

      });

      return this;

    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant