我有一个具有这些功能的视图 -
initialize:=>
@populateSearchHistory()
@el
populateSearchHistory:=>
console.log(pastSearches)
@$el.find("#searchHistoryContainer").append(Handlebars.templates["$$ uri $$-searchHistory"]())
@collection.add(stuff)
@collection.on "add", (toAdd)->
console.log(toAdd)
但未记录“添加”。发生了什么事?
UPDATE -
我尝试在初始化函数中执行此操作 -
initialize:=>
@collection.on "add", @populateSearchHistory
其中populateSearchHistory现在是
populateSearchHistory:(toAdd)=>
console.log(toAdd)
但是,toAdd是一个空模型,我需要它来获取我添加的值。
UPDATE-编译的javascript
var _this = this;
({
initialize: function() {
_this.populateSearchHistory();
return _this.el;
},
populateSearchHistory: function() {
console.log(pastSearches);
_this.$el.find("#searchHistoryContainer").append(Handlebars.templates["$$ uri $$-searchHistory"]());
return _this.collection.add(stuff);
}
});
this.collection.on("add", function(toAdd) {
return console.log(toAdd);
});
更新
好的 - 所以init函数中的绑定工作,并且传入的未初始化查询是因为我有一个for循环遍历集合并在集合中添加每个模型 - 每个模型都未定义 - 为什么会发生这种情况?
答案 0 :(得分:0)
这里jsfiddle(已更新):http://jsfiddle.net/85YxD/
SearchModel = Backbone.Model.extend();
SearchCollection = Backbone.Collection.extend({
model : SearchModel
});
myCollection = new SearchCollection();
SearchView = Backbone.View.extend({
initialize: function() {
var _this = this;
_this.populateSearchHistory();
},
populateSearchHistory: function() {
var _this = this;
// your code here
var stuff = new SearchModel({
key : 'value'
})
//model can be added both way
console.log('model1 added.......');
_this.options.list.add(stuff);
//Or,
console.log('model2 added.......');
_this.options.list.add({
key1 : 'value1',
key2 : 'value2'
});
//TODO : add loop for adding models here
return _this;
}
});
myCollection.on("add", function(toAdd) {
console.log('added model', toAdd);
console.log('updated collection', myCollection.toJSON());
});
new SearchView({
list : myCollection
});