在 Backbone.js 子视图中触发事件
我有一个包含表格的视图。
var newsIndexView = Backbone.View.extend({
...
});
表中的每一行都是与模型关联的另一个视图。
var newsItemView = Backbone.View.extend({
tagName: "tr",
...
selectRow: function(e){
this.selected = !this.selected;
$(this.el).toggleClass("selected");
if(this.selected){
$(".delete_many").on("click", $.proxy(this.remove, this));
}else{
$(".delete_many").off("click", $.proxy(this.remove, this));
}
},
...
});
用户可以选择行。当选择 1 行或多行时,会出现删除按钮。当选择按钮(.delete_many)时,我想触发每个选定的 newsItemView 的删除事件。正如您所看到的,当选择一行时,我为其添加一个事件处理程序,并在取消选择时将其删除。我想知道是否有更好的方法来做到这一点?
I have a view that includes a table.
var newsIndexView = Backbone.View.extend({
...
});
Each Row in the table is another view associated with a model.
var newsItemView = Backbone.View.extend({
tagName: "tr",
...
selectRow: function(e){
this.selected = !this.selected;
$(this.el).toggleClass("selected");
if(this.selected){
$(".delete_many").on("click", $.proxy(this.remove, this));
}else{
$(".delete_many").off("click", $.proxy(this.remove, this));
}
},
...
});
The user can select rows. When 1 or more rows are selected a delete button appears. When the button (.delete_many) is selected I want to trigger the delete event for each selected newsItemView. As you can see when a row is selected I'm adding an event handler for it, and removing it when it is unselected. I was wondering if there is a better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在管理表的视图上使用 delegateEvents 来安装点击处理程序一次?即使稍后添加按钮,它也应该触发(即使稍后删除按钮,它也应该保留)。
然后,deleteMany 函数将找出选择了哪些行并在循环中删除它们。由于按钮属于整个表(而不是单个行),这似乎更自然。它还可以轻松地出现“您确定吗”确认对话框(您只想弹出一次而不是每一行),并使用服务器后端的批量删除功能(一个请求而不是每行一个请求) )。
Couldn't you use delegateEvents on the view that manages the table to install the click handler once? It should fire, even if the buttons were added later (and stay around even if the buttons are removed later).
The deleteMany function would then figure out which rows are selected and remove them in a loop. Since the button belongs to the table as a whole (and not to individual rows) this seems to be more natural. It would also make it easy to have a "are you sure" confirmation dialog (that you want to pop up just once and not for every row), and using bulk delete features of your server backend (one request instead of one for each row).