2012-08-15 24 views
0

我想讓我的ApplicationView監聽路由器上的所有事件。它的工作原理,如果我這樣做:骨架怪異TypeError error.bind('all','update')?

this.model.router.on('route:myroute1, 'update'); 
this.model.router.on('route:myroute2, 'update'); 
this.model.router.on('route:myroute3, 'update'); 

當我嘗試綁定all事件:

this.model.router.bind('all', 'update'); 

我得到了這個可怕的錯誤:

TypeError: all[i].apply is not a function

all[i].apply(all[i + 1] || this, args);

視圖(定義爲requirejs模塊):

define(['backbone', 'lodash'], function(Backbone, _) { 

    return Backbone.View.extend({ 

     el: 'body', 

     initialize: function() { 
      this.model.router.bind('all', 'update'); 

      _.bindAll(this, 'render', 'update'); 
      this.render(); 
     }, 

     render: function() { }, 

     update: function(route) { 
      this.$el 
       .find('.nav-collapse a[href=#'+ route +']') 
       .parent() 
        .addClass('active') 
        .siblings() 
         .removeClass('active'); 
     } 

    }); 

}); 

雖然這是其中錯誤在原始源代碼發生的情況:

// Execute "all" callbacks. 
if (all) { 
    args = [event].concat(rest); 
    for (i = 0, length = all.length; i < length; i += 2) { 
     all[i].apply(all[i + 1] || this, args); 
    } 
} 

回答

2

on()/bind()的第二個參數被認爲是一個功能。這是一個無證的功能,你可以傳遞一個字符串嗎?在那種情況下,它調用了那個方法的對象是什麼?你確定它在你的第一個案件中起作用嗎?

如果你這樣做,而不是?:

this.model.router.bind('all', this.update); 
+0

發生什麼,似乎你說得對......不應該在第一種情況下工作,同時.​​.. – gremo 2012-08-15 11:12:26

+0

是啊,我只是看着骨幹源它看起來不像它會支持傳遞一個字符串作爲第二個參數。此外,它看起來像你想要這樣註冊事件監聽器,與上下文參數:'this.model.router.on('all',this.update,this);' – JMM 2012-08-15 11:15:43

+0

'this.model .router.bind('all',this.update);'是錯誤的,因爲它會立即調用該函數... – gremo 2012-08-15 11:19:59