javascript - 在 BackBone js 中调用 javascript 渲染 View 。渲染后回调?

标签 javascript view backbone.js

看哪,主干 View 渲染调用:

render: function() {
  $(this.el).html(this.template({title: 'test'}));  //#1
  this.renderScatterChart();
  return this;
},

所以,我将标准渲染称为#1。然后,我调用一个方法 [这次,它是图表库的包装器] 来查找 div。 div 由 render 调用渲染。但此时,它还没有附加到 DOM(对吗?)。所以图表调用不幸地死掉了。

这个的模式是什么?我很想知道有一个渲染后回调。我已经尝试了一些解决这个问题的技巧,有时我可以让图表工作,但事件不会绑定(bind)。

最佳答案

我处理这类事情的常用方法是使用 setTimeout超时为零,以便在浏览器再次获得控制权后安排发生一些事情。试试这个:

render: function() {
    $(this.el).html(this.template({title: 'test'}));

    var _this = this;
    setTimeout(function() {
        _this.renderScatterChart();
    }, 0);

    return this;
}

或者,如果 renderScatterChart 已绑定(bind)到相应的 this:

render: function() {
    $(this.el).html(this.template({title: 'test'}));
    setTimeout(this.renderScatterChart, 0);
    return this;
}

您还可以使用_.defer如果您想更明确地说明自己在做什么:

defer _.defer(function, [*arguments])

Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0.

所以你也可以这样做:

// Assuming that `renderScatterChart` is bound to the appropriate `this`...
render: function() {
    $(this.el).html(this.template({title: 'test'}));
    _(this.renderScatterChart).defer();
    return this;
}

// or if it isn't bound...
render: function() {
    $(this.el).html(this.template({title: 'test'}));

    var _this = this;
    _(function() {
        _this.renderScatterChart();
    }).defer();

    return this;
}

关于javascript - 在 BackBone js 中调用 javascript 渲染 View 。渲染后回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9145680/

相关文章:

javascript - 休息API : user-agent-based client (app) authorization

ruby-on-rails - Rails View : creating a menu

带有布局的 Android 轮播效果

django - Backbone.js 发布 500 错误

javascript - 在事件回调中获取对模型的引用

javascript - 使用数组模型维护 knockout.js 中的 UI 状态

javascript - 刷新 ng-repeat 即使没有任何改变

javascript - 通过 JS 添加类时隐藏 div

mysql - 如何在创建 View 时不扩展 `*`

javascript - subview 的主干事件未正确触发