嘿!我是 Backbone.js 的新手,所以这很可能是一个简单的问题。
我想在每次更改时控制台记录我的 friend 收藏。所以我绑定(bind)了集合中的 all
事件来调用我的 logFunction.. 但是在 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;
最佳答案
在您的 AppView.initialize
中,您应该调用 _.bindAll(this, 'logFriendsCollection')
将 this
绑定(bind)到 AppView
。
关于javascript - 记录 Backbone.js 集合中的更改,我的集合未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6152664/