Javascript 绑定到集合的主干视图未拾取添加事件
我有一个具有这些功能的视图-Javascript 绑定到集合的主干视图未拾取添加事件,javascript,backbone.js,coffeescript,Javascript,Backbone.js,Coffeescript,我有一个具有这些功能的视图- initialize:=> @populateSearchHistory() @el populateSearchHistory:=> console.log(pastSearches) @$el.find("#searchHistoryContainer").append(Handlebars.templates["$$ uri $$-searchHistory"]()) @collection.add
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)
但“添加”未被记录。发生了什么事
更新-
我尝试在初始化函数中执行此操作-
initialize:=>
@collection.on "add", @populateSearchHistory
大众研究历史现在在哪里
populateSearchHistory:(toAdd)=>
console.log(toAdd)
但是,toAdd是一个空模型,我需要它具有我添加的值
更新编译的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循环遍历集合并在集合中添加每个模型-每个模型都未定义-为什么会发生这种情况?这里是jsfiddle(已更新):
呃..不是真的-当我复制和粘贴时,它被搞砸了-我很确定我真正的缩进是正确的,因为咖啡没有对我大喊大叫,我可以发布编译好的javascriptWhy you's use=>而不是->这已经是你的视图对象了,所以你不需要使用它(_this)。您还应该在init方法中处理所有模型/集合事件侦听器。
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
});