javascript - setElement 后 Backbone 事件未委托(delegate)给新元素

标签 javascript backbone.js underscore.js

我正在使用 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/

相关文章:

javascript - 为什么 .on() 可以工作但 .listenTo() 失败?

javascript - 主干 - 未为模型定义 model.destroy() 函数

javascript - 如何在 ASP.NET - MVC 上使用 javascript 将 DropDownListFor 值更改回 null?

javascript - Internet Explorer 11 中的 crypto.getRandomValues 有什么问题?

javascript - 当 View 位于 Fancybox 内时,我无法触发 Backbone.js 事件

javascript - 下划线JS : get 5 items per category

javascript - 将对象数组转换为一个对象

javascript - 当源是 base64 websocket 数据时,图像 onload 不会触发 javascript

Javascript:事件监听器中未定义 event.target.id

javascript - 从 BackboneJS 集合/UnderscoreJS 数组中提取模型