嘿! Im新的Backbone.js,所以這很可能是一個簡單的問題。Backbone.js Collection中的日誌更改,我的收藏夾未定義
我想每次改變時我的朋友集合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;
嗯,也許我missunderstood你...但這是改變的代碼是什麼樣子,並且this.friends仍然未定義:http://jsfiddle.net/UNkMp/1/embedded/result/ – Anders 2011-05-27 13:28:39
現在看起來它應該可以工作,它在我調用'appview.logFriendsCollection()'後調用'新的AppView'。你在哪裏調用'logFriendsCollection()'? – ponzao 2011-05-27 14:06:17
我以爲這會在集合中觸發任何事件時調用它:'this.bind(「all」,options.view.logFriendsCollection);'在Friends集合中。我希望每次收集被改變時都會調用它... – Anders 2011-05-27 14:27:33