JS/Backbone/Chaplin 事件处理程序未触发

JS/Backbone/Chaplin event handler not triggering

本文关键字:程序 事件处理 Backbone Chaplin JS      更新时间:2023-11-12

我在卓别林视图中将事件处理程序绑定到动态生成的元素上时遇到问题,并且无法弄清楚发生了什么。这似乎是最明确的实现:

var MyView = Chaplin.View.extend({
    /* using jQuery to bind the event because Chaplin.View.listen
       and Chaplin.View.delegate aren't working... */
    render: function() {
        Chaplin.View.prototype.render.apply(this, arguments);
        this.$('#the-button').click(function() { console.log('clicked'); });
        console.log('breakpoint here');
    }
});

在 Chrome 开发工具中:

> this.$('#the-button').attr('unique-attr', 'blah');
< [  <button id="the-button" unique-attr="blah">Text</button>]
> this.$('#the-button').click()
   clicked
< [  <button id="the-button" unique-attr="blah">Text</button>]

取消暂停应用程序,确保我们查看的是相同的元素:

> $('#the-button')
< [  <button id="the-button" unique-attr="blah">Text</button>]
> $('#the-button').click()
   [ no output ]
< [  <button id="the-button" unique-attr="blah">Text</button>]

任何人都可以解释为什么按钮的 onclick 事件处理程序在"渲染"函数的范围内触发,但不在全局范围内触发?谢谢。

解决了。

我指的是父视图中的MyView.$el.html()。这将返回元素的内部 HTML。但是事件处理程序绑定到$el根,该根不再呈现到文档中,因此没有调用事件处理程序。