Log changes in Backbone.js Collection, my collection is undefined
Hey! Im new to Backbone.js, so this is most likely an easy question.
I'm want to console.log my friends collection each time it's changing. So i have binded all
events in the collection to call my logFunction.. but in the logfunction this.friends
is undefined. Why?
This is my "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 开发者_JS百科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;
In your AppView.initialize
you should call _.bindAll(this, 'logFriendsCollection')
to bind this
to AppView
.
I think that when you bind the view's logFriendsCollection
method to the the Friend collection that the method also receives the collection's context. So when you reference this
in the method, this
refers to the collection rather than the view.
I was messing around with it on your Fiddler link, and the code that I changed to make it work was
logFriendsCollection: function () {
console.log("Friends", this);
}
精彩评论