开发者

Backbone.js views delegateEvents do not get bound (sometimes)

I'm using Backbone.js and sometimes the views events do not get bound correctly.

I can check the event binding situation with $(viewselector).data() in jQuery. Most of the time there are events, sometim开发者_运维知识库es there aren't!

Are there any known things I should watch out for that can cause this?


Events are delegated to this.el when the view is initialized. So you need to:

  • Create the view by giving the constructor the "el" option to specify the element
  • Define el, tag, id, classname on your view to create or find on the page your element directly.
  • Append your rendered view to the "el" element of the view
  • Make sure you do not replace the "el" element after the view creation

For the last item, if you have to do it, you can call delegateEvents once more to re-delegate the event on your view.


My approach in these scenarios is to add delegateEvents() in render of each view that has an event, like the following:

  $(this.el).empty();
  $(this.el).html(this.template({}));
  this.delegateEvents(); // this will bind all events ONCE AGAIN

This is perfect for views specially created dynamically i.e. views that are declared new under each click or so...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜