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

时间:2015-02-13 15:16:34

标签: javascript backbone.js

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

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事件处理程序在&#34; render&#34;的范围内被触发。功能,但不是在全球范围内触发?感谢。

1 个答案:

答案 0 :(得分:0)

解决了它。

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