在Backbone.js Collection中记录更改,我的集合未定义

时间:2011-05-27 13:08:45

标签: javascript model-view-controller backbone.js

喂!我是Backbone.js的新手,所以这很可能是一个简单的问题。

我想在每次更改时都登录我的朋友收藏。所以我在集合中绑定了all个事件来调用我的logFunction ..但是在logfunction this.friends中是未定义的。为什么呢?

这是我的“app”:

(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;

2 个答案:

答案 0 :(得分:2)

AppView.initialize中,您应致电_.bindAll(this, 'logFriendsCollection')this绑定到AppView

答案 1 :(得分:0)

我认为当您将视图的logFriendsCollection方法绑定到Friend集合时,该方法也会接收集合的上下文。因此,当您在方法中引用this时,this指的是集合而不是视图。

我在你的Fiddler链接上乱搞它,我改变它以使其工作的代码是

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