我正在尝试将点击事件绑定(bind)到主干 View 的顶级标签。目前看起来是这样的:
var PageSize = Backbone.View.extend({
tagName: 'option',
className: "setPageSize",
initialize: function(options) {
this.value = options.value;
this.text = options.text;
},
template: _.template(
"<%=text%>"
),
render: function() {
this.$el.html(this.template({text: this.text}));
return this;
},
events: {
'click .setPageSize': 'setPageSize'
},
setPageSize: function() {
console.log(this.value);
},
});
module.exports = PageSize;
这些 PageSize View 的一堆由另一个 View 实例化,该 View 将它们附加到 <select>
标签。我相当确定其他 View 不是问题,因为 <option>
标签确实出现在 <select>
中用正确的文本标记。
我遇到的问题是点击事件,当给定 <option>
时应该触发该事件标签被点击,永远不会触发。我认为这是因为点击事件监视的类是最外层标签的一部分(用 tagName
和 className
指定的标签),由于某种原因,它没有附加事件监听器。
我认为我需要以某种方式将单击事件绑定(bind)到整个 View 而不是其中的模板项,但我完全不确定如何去做。我尝试过 this.setElement(this.$el.html())
但这样做会使 <option>
都不再有效。标签显示在<select>
中完全没有。
最佳答案
来自主干文档 delegateEvents (重点是我添加的)
Uses jQuery's on function to provide declarative callbacks for DOM events within a view. If an events hash is not passed directly, uses this.events as the source. Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element (this.el).
问题出在您的事件对象中。基本上,因为您添加了“类选择器”,所以单击事件只会针对 View 元素中具有“.setPageSize”类的元素进行处理。然而,该类位于 View 元素本身上,而不位于其任何子元素上,因此处理程序永远不会被调用。
通过更改:
events: {
'click .setPageSize': 'setPageSize'
},
对此:
events: {
'click': 'setPageSize'
},
使事件绑定(bind)到 View 的根元素 (this.el)。换句话说, View 本身。
关于javascript - 将点击事件绑定(bind)到 Backbone View 的顶级标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50494827/