Эй! Я новичок в Backbone.js, так что это, скорее всего, простой вопрос.
Я хочу console.log моей коллекции друзей каждый раз, когда она меняется. Поэтому я связал all
события в коллекции, чтобы вызвать мою функцию 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;