javascript - Backbone.js 在 View 中获取渲染回调

标签 javascript jquery backbone.js

我有一个 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();

如果您的插件需要渲染其元素(也许它需要大小和位置信息),那么您将不得不进行一些组装:

  1. 调用者可以在将 View 添加到 DOM 后调用该 View 上的方法。
  2. 您可以使用setTimeout(..., 0) or _.defer在浏览器更新 DOM 之后绑定(bind)插件。不过,只有当每个人都使用通用的 x.append(v.render().el) 模式时,这才有效。

关于javascript - Backbone.js 在 View 中获取渲染回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126642/

相关文章:

javascript - 是否可以让多个脚本调用同一个脚本?

javascript - FitText.js 的非 jQuery 替代品?

jquery - 捕获坐标并在其上显示 div

javascript - git log命令逻辑解释 git log master-1.0.83..HEAD

javascript - 使用javascript自动打开页面

javascript - 创建和测试单个 Javascript 嵌套函数

javascript - 主干 subview 事件未触发

jquery - 创建响应式 GridView 横幅

javascript - backbone remove view 删除 el

javascript - Backbone.js 自定义集合排序