Javascript Backbone.js 视图 delegateEvents 没有被绑定(有时)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5125958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:46:12  来源:igfitidea点击:

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

javascriptjavascript-eventsbackbone.js

提问by FriiSource

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

我正在使用 Backbone.js,有时视图事件没有正确绑定。

I can check the event binding situation with $(viewselector).data()in jQuery. Most of the time there are events, sometimes there aren't!

我可以$(viewselector).data()在 jQuery 中检查事件绑定情况。大多数时候有事件,有时没有!

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

是否有任何我应该注意的已知事情会导致这种情况?

回答by Julien

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

当视图初始化时,事件被委托给 this.el。所以你需要:

  • 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
  • 通过为构造函数提供“el”选项来指定元素来创建视图
  • 在您的视图上定义 el、tag、id、classname 以直接在页面上创建或查找您的元素。
  • 将渲染视图附加到视图的“el”元素
  • 确保在创建视图后不要替换“el”元素

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

对于最后一项,如果您必须这样做,您可以再次调用 delegateEvents 以在您的视图上重新委托该事件。

回答by Varand Pezeshkian

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

我在这些场景中的方法是添加delegateEvents()具有事件的每个视图的渲染,如下所示:

  $(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...

这对于专门动态创建的视图来说是完美的,即在每次点击左右时声明为新的视图......