简体   繁体   中英

JS/Backbone/Chaplin event handler not triggering

I'm having trouble binding an event handler on a dynamically-generated element in a Chaplin view, and I can't figure out what's going on. This seems like the most explicit possible implementation:

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');
    }
});

In Chrome Dev Tools:

> 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>]

Unpause the application, make sure we're looking at the same element:

> $('#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>]

Can anybody please explain why the onclick event handler for the button is being triggered in the scope of the "render" function but not being triggered in the global scope? Thanks.

Solved it.

I was referring to MyView.$el.html() in a parent view. That returns the inner HTML of the element. But the event handler was binding to the root of $el , which was no longer being rendered into the document, thus no event handlers were being called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM