[英]Backbone.js Collection Method Binding
我目前正在使用Backbone.js集合和视图,并且尝试将集合函数绑定到视图内部的函数。 我以为我可以在集合内部简单地创建一个函数,然后在视图内部绑定它。 不幸的是,它一直在引用collections方法。 这是我的代码。
var RightPaneCollectionView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render', 'add', 'remove', 'remove_by_name'); // bind the methods to this scope
this.el.html(""); // clear out the view
this.collection.bind('removeByName', this.remove_by_name);
this.collection.bind('remove', this.remove);
},
remove_by_name: function(){ console.log("Removing by name inside view.")
}
}
var RightPaneCollection = Backbone.Collection.extend({
model: RightPaneButtonModel,
url: "",
removeByName: function(){
console.log("Removing by name inside collection");
}
});
我想能够摔倒
rightPaneCollection.removeByName("foo");
并引用该视图。 我不确定我是否会以正确的方式进行操作。 当前,通过引用视图内部的remove方法,删除操作可以正常工作。
感谢您的帮助!
这是你想要的?
基本上,删除项目时,我会从集合中触发“ removeByName”事件,并传递被删除项目的名称。 在视图中,我绑定到该事件名称,并调用视图的函数并访问要删除的项目的名称。
var RightPaneCollectionView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'remove_by_name');
this.el.html(""); // clear out the view
this.collection.bind('removeByName', this.remove_by_name);
},
remove_by_name: function(name){
console.log("Removing by name inside view: " + name)
}
}
var RightPaneCollection = Backbone.Collection.extend({
model: RightPaneButtonModel,
url: "",
removeByName: function(name){
var itemToRemove = this.find(function(item){return item.get("name") === name;});
if(itemToRemove) {
this.remove(itemToRemove);
this.trigger("removeByName", name);
}
}
});
我不确定,但是您不必手动触发事件吗?
var RightPaneCollection = Backbone.Collection.extend({
model: RightPaneButtonModel,
url: "",
removeByName: function(){
console.log("Removing by name inside collection");
this.trigger('removeByName');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.