我正在使用 Underscore 模板实现主干 View 。使用 setElement 函数将 View el 替换为模板 html。该函数的声明说“...将 View 的委托(delegate)事件从旧元素移动到新元素”,但由于某种原因,这不起作用。为什么这不能按照 Backbone 声明中的描述工作?
这是一个情况示例( View 的相关部分):
initialize: function(args) {
_.extend(this, args);
this.listenTo(this.model, 'change', this.render);
},
events: {
'click .active-area': '_test'
},
_test: function() {
// After "setElement" this doesn't fire anymore.
this.model.set('color', 'green');
},
render: function() {
// After this the "click" listener no longer exists.
this.setElement(this.template(this.model.toJSON());
return this;
}
最佳答案
this.template(...)
不是 DOM 中的元素。
在您的代码中,setElement
从旧元素中删除事件监听器,然后将它们委托(delegate)给新元素,它只存在于内存中,不存在于页面中。
您应该只更改当前元素的内容。
this.$el.html(this.template(this.model.toJSON()));
I need to replace the whole element html with the template html and that's why I need to use the
setElement
function.
假设您有以下 HTML:
<div id="currentView"><!-- view's root (el) -->
<button type="button" class="active-area">Click me</button>
<span class="color"><%= color %></span>
</div>
添加一个包装 div 并将 #currentView
div 移动到模板中。
<div class="wrapper"><!-- view's root (el) -->
<div id="currentView">
<button type="button" class="active-area">Click me</button>
<span class="color"><%= color %></span>
</div>
</div>
现在 this.$el.html
将交换整个元素。
如果你真的想让 View 交换它自己的根元素,你可以创建一个新元素,然后使用 jQuery 的 replaceWith
将新元素替换为旧元素。
render: function() {
// create a new element from the template
var $newEl = $(this.template(this.model.toJSON()));
// completely replace the current element in the DOM
this.$el.replaceWith($newEl);
// then tell the view
this.setElement($newEl);
return this;
}
关于javascript - setElement 后 Backbone 事件未委托(delegate)给新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949779/