2011-05-27 71 views
1

嘿! Im新的Backbone.js,所以這很可能是一個簡單的問題。Backbone.js Collection中的日誌更改,我的收藏夾未定義

我想每次改變時我的朋友集合console.log。所以我已經在集合中綁定了all事件來調用我的logFunction ..但是在日誌函數this.friends中未定義。爲什麼?

這是我的 「應用程序」:

(function ($) { 


     Friend = Backbone.Model.extend({ 
      //Create a model to hold friend atribute 
      name: null 
     }); 


     Friends = Backbone.Collection.extend({ 

      model: Friend, 
      //This is our Friends collection and holds our Friend models 
      initialize: function (models, options) { 
       this.bind("add", options.view.addFriendLi); 
       this.bind("all", options.view.logFriendsCollection); 

       //Listen for new additions to the collection and call a view function if so 
      } 
     }); 

     window.AppView = Backbone.View.extend({ 
      el: $("body"), 

      initialize: function() { 
       this.friends = new Friends(null, { view: this }); 
      }, 

      events: { 
       "click #add-friend": "showPrompt" 
      }, 


      showPrompt: function() { 
       var friend_name = prompt("Who is your friend?"); 
       var friend_model = new Friend({ "name": friend_name }); 

       this.friends.add(friend_model); 
      }, 

      addFriendLi: function (model) { 
       $("#friends-list").append("<li>" + model.get('name') + "</li>"); 

      }, 

      logFriendsCollection: function (args) { 
       console.log("Friends", this.friends); 
      } 

     }); var appview = new AppView; 

回答

0

我認爲,當您將視圖的logFriendsCollection方法綁定到Friend集合時,該方法也會收到集合的上下文。所以當你在方法中引用this時,this引用的是集合而不是視圖。

我與它搞亂你的周圍提琴手鍊接,和我改變,使它的代碼工作是

  logFriendsCollection: function() { 
       console.log("Friends", this); 
      } 
2

在你AppView.initialize你應該叫_.bindAll(this, 'logFriendsCollection')綁定thisAppView

+0

嗯,也許我missunderstood你...但這是改變的代碼是什麼樣子,並且this.friends仍然未定義:http://jsfiddle.net/UNkMp/1/embedded/result/ – Anders 2011-05-27 13:28:39

+0

現在看起來它應該可以工作,它在我調用'appview.logFriendsCollection()'後調用'新的AppView'。你在哪裏調用'logFriendsCollection()'? – ponzao 2011-05-27 14:06:17

+0

我以爲這會在集合中觸發任何事件時調用它:'this.bind(「all」,options.view.logFriendsCollection);'在Friends集合中。我希望每次收集被改變時都會調用它... – Anders 2011-05-27 14:27:33