简体   繁体   中英

Backbone JS event does not trigger for dynamically added elements

I have a Backbone View that renders an external Handlebars template (*.hbs). This view is rendered inside of another View where it is instantiated, essentially:

MainAppView
render: function() {
//load main layout
var childView = new ChildView();
}


ChildView

render: function() {
$('body').append(this.template(data));
}

template:

<ul id="someId">
<li><a> {{data}}</a></li>
</ul>

and an events hash in the childView like this:

events: {
  'click #someId li a' : 'doSomething'
}

doSomething: function() { event.preventDefault(); console.log("exit");} 

That's the gist of it. The problem, the selector #someId li a does not work and it fails to perform doSomething

I verified the selector with jQuery, by binding the function doSomething in the Chrome console, that works fine.

I think I know why it doesn't work in Backbone though, the HBS template is rendered after delegateEvents is fired off when the ChildView is instantiated, which means there exist no elements by the selector I am using and hence nothing was bound. I tried prefixing with a body, but nah, did not work either.

What do I need to do?

Your ChildView render method is rendering the contents of the view into the body rather than inside itself. You render should look something like this:

render: function() {
    this.$el.append(this.template(data));
    $('body').append(this.$el);
}

The reason the doSomething function wasn't being called is because events in Backbone are delegated to the root element of the view ( view.el ). The following is basically what Backbone is doing under the hood:

'click #someId li a' : 'doSomething'

becomes

view.$el.on('click', '#someId li a', view.doSomething);

If you go and append the template content directly to the body instead of the view's el, the events will never be caught by the view and thus the callbacks aren't called.

我认为doSomething函数缺少参数event因此添加参数:

doSomething: function(e) { e.preventDefault(); console.log("exit");} 

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