我有一个 Backbone 应用程序,我们有这样的东西:
render: function() {
this.$el.html(_template());
$('#id').plugin();
return this;
}
#id
来自正在渲染的元素。这仅有时有效,因为它实际插入到 dom 中可能需要更长的时间。
在调用我们的 plugin()
函数之前,此 View 中是否有一种方法可以定义回调或以某种方式确定 dom 已更新?
谢谢!
最佳答案
你的问题是这样的:
$('#id').plugin();
正在 DOM 中查找 #id
,但 this.$el
尚未在 DOM 中;因此,如果 #id
位于 this.$el
内,则 #id
也不在 DOM 中,并且 $(' #id')
将为空。您想要在 this.$el
中查找 #id
,而 Backbone 提供 this.$
shortcut为此:
$ (jQuery or Zepto)
view.$(selector)
If jQuery or Zepto is included on the page, each view has a $ function that runs queries scoped within the view's element. [...] It's equivalent to running:
view.$el.find(selector)
.
所以你想这样做:
this.$('#id').plugin();
如果您的插件需要渲染其元素(也许它需要大小和位置信息),那么您将不得不进行一些组装:
- 调用者可以在将 View 添加到 DOM 后调用该 View 上的方法。
- 您可以使用
setTimeout(..., 0)
or_.defer
在浏览器更新 DOM 之后绑定(bind)插件。不过,只有当每个人都使用通用的x.append(v.render().el)
模式时,这才有效。
关于javascript - Backbone.js 在 View 中获取渲染回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126642/