问题描述
||
嘿!我不是Backbone.js的新手,所以这很可能是一个简单的问题。
我希望每次更改时都可以console.log我的朋友收藏。所以我已经绑定了集合中的“ 0”事件来调用我的logFunction ..,但是在日志函数中“ 1”是未定义的。为什么?
这是我的“应用”:
(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;
解决方法
我认为,当您将视图的
logFriendsCollection
方法绑定到Friend集合时,该方法也会接收该集合的上下文。因此,当您在方法中引用this
时,this
是指集合而不是视图。
我在您的Fiddler链接上弄乱了它,为使它起作用而进行了更改的代码是
logFriendsCollection: function () {
console.log(\"Friends\",this);
}
, 在您的AppView.initialize
中,应调用_.bindAll(this,\'logFriendsCollection\')
将this
绑定到AppView
。