2011-11-02 128 views
2

我有兩個Backbone集合。我想綁定到一個重置事件。當該事件被觸發,我想打電話給取的第二集合,就像這樣:將collection.fetch作爲命名函數傳遞給collection.bind不起作用

App.collections.movies.bind("reset", App.collections.theaters.fetch); 

第二取不閃光,但。但是,如果我通過一個匿名函數調用aters.fetch,它可以正常工作:

App.collections.movies.bind("reset", function() { App.collections.theaters.fetch(); }); 

任何想法爲什麼會出現這種情況?

繼承人我的完整代碼。我沒有表現出任何模型或集合,因爲它是一個大量的代碼,但讓我知道,如果你認爲這可能是問題的根源:

var App = { 

    init: function() { 
     App.collections.theaters = new App.Theaters(); 
     App.collections.movies = new App.Movies(); 

     App.events.bind(); 
     App.events.fetch(); 

    }, 

    events: { 
     bind: function() { 
      App.collections.theaters.bind("reset", App.theaterManager.assign); 

      App.collections.movies.bind("reset", function() { App.collections.theaters.fetch(); }); 
     }, 

     fetch: function() { 
      App.collections.movies.fetch(); 
     } 
    }, 

    collections: {}, 

    views: {}, 

    theaterManager: { 

     // Provide each model that requires theaters with the right data 
     assign: function() { 
      // Get all theaters associated with each theater 
      App.theaterManager.addToCollection("theaters"); 

      // Get all theaters associated with each movie 
      App.theaterManager.addToCollection("movies"); 
     }, 

     // Add theaters to a collection 
     addToCollection: function (collection) { 
      App.collections[collection].each(function (item) { 
       item.theaters = App.theaterManager.getTheaters(item.get(("theaters"))); 
      }); 
     }, 

     // Returns a collection of Theaters models based on a list of ids 
     getTheaters: function() { 
      var args; 

      if (!arguments) { 
       return []; 
      } 

      if (_.isArray(arguments[0])) { 
       args = arguments[0]; 
      } else { 
       args = Array.prototype.slice.call(arguments); 
      } 

      return new App.Theaters(_.map(args, function (id) { 
       return App.collections.theaters.get(id); 
      })); 
     } 
    } 
}; 

$(function() { 
    App.init(); 
}); 

回答

2

這一切都與功能方面做。在Javascript中調用函數的方式是一個常見的混淆。

在第一種方式中,您正在處理要調用的函數,但沒有定義上下文。這意味着任何人稱它會成爲「這個」。很可能相當於打電話App.collections.movies.fetch()這不是你想要的。至少,我猜這就是上下文的內容。很難確定......它可能是jQuery,它可能是Backbone.sync。要告訴的唯一方法是在Backbone.collections.fetch函數中放置斷點並打印出this變量。無論如何,這不會是你想要的。

在第二種情況下,您再次將它交給一個函數,但在內部指定調用該函數的上下文。在這種情況下,fetchApp.collections.theaters作爲上下文被調用。

......那是清楚的嗎?

+0

明白了。我需要做的是在綁定事件時傳遞上下文。骨幹允許你這樣做:collection.bind(「event」,handle,context) – Adam

+0

好吧,你去!我沒有意識到'colleciton.bind'讓你有能力傳遞上下文。贏得! –

+0

我試過傳遞一些不同的上下文,但都沒有工作。我試過這個,它只是窗口對象,App.collections.theaters和App.collections.movi​​es。仍然沒有運氣。 – Adam

相關問題