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

Log changes in Backbone.js Collection, my collection is undefined

本文关键字:集合 我的 未定义 记录 Backbone js      更新时间:2023-09-26

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

每次我的好友收藏发生变化时,我都想安慰一下。因此,我在集合中绑定了all事件来调用我的logFunction。。但是在logfunction中CCD_ 2是未定义的。为什么?

这是我的"应用程序":

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

AppView.initialize中,您应该调用_.bindAll(this, 'logFriendsCollection')this绑定到AppView

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

我在你的Fiddler链接上摆弄它,我更改的代码是

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