2

我有一个 Backbone 应用程序,我们有这样的东西:

render: function() {

   this.$el.html(_template());

   $('#id').plugin();

   return this;
}

来自#id正在渲染的元素。这只有时有效,因为它可能需要更长的时间才能真正插入 dom。

在调用我们的函数之前,在这个视图中是否有办法定义回调或以某种方式确定 dom 已更新plugin()

谢谢!

4

3 回答 3

3

你的问题是这样的:

$('#id').plugin();

正在 DOM 内部寻找,#idthis.$el尚未在 DOM 中;所以,如果#id是 inside this.$el,那么#id也不在 DOM 中并且$('#id')将为空。#id你想在里面寻找this.$el,Backbone 提供了this.$快捷方式

$ (jQuery 或 Zepto) view.$(selector)

如果页面中包含 jQuery 或 Zepto,则每个视图都有一个$函数,用于运行视图元素范围内的查询。[...] 这相当于运行:view.$el.find(selector).

所以你想这样做:

this.$('#id').plugin();

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

  1. 在将视图添加到 DOM 后,调用者可以调用视图上的方法。
  2. 您可以在浏览器更新 DOM后使用setTimeout(..., 0)_.defer绑定插件。这仅在每个人都使用通用模式时才有效。x.append(v.render().el)
于 2012-10-29T18:24:10.600 回答
0

Symply 触发事件:

MyView = Backbone.View.extend({

    initialize: function(){
        this.on('view:rendered', this.initPlugin, this);
    },
    render: function(){
        this.$el.html(_template());
        this.trigger('view:rendered', this/*or some useful data*/)
    },
    initPlugin: function(){
        this.$('#id').plugin()//watch on this.$ to apply selector inside this view only
    }
于 2012-10-29T18:00:08.773 回答
0

我不确定,但试试看

将其作为事件绑定到视图,在呈现视图后触发它

var viewobject = {};

_.extend(viewobject, Backbone.Events);

viewobject.on("alert", function(msg) {
  $('#id').plugin();
});

object.trigger("alert", "an event");
于 2012-10-29T18:07:31.353 回答