在BackBone js中的渲染视图上调用javascript.后渲染回调?

wha*_*ird 22 javascript view backbone.js

看,骨干视图呈现通话:

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

所以,我在#1处调用标准渲染.然后,我调用一个方法[这一次,它是图表lib的包装],寻找一个div.div由渲染调用呈现.但是在这一点上,它还没有附加到DOM(对吧?).所以图表召唤可悲地死了.

这个模式是什么?我很高兴听到有一个后渲染回调.我已经尝试过几次黑客攻击,有时候我会让图表工作,但事件并没有结合.

mu *_*ort 45

我通常采用的方法是使用setTimeout零超时来安排一旦浏览器再次获得控制就会发生某些事情.试试这个:

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

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

    return this;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果renderScatterChart已经绑定到适当的this:

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

您也可以使用_.defer,如果你想更明确的了解你在做什么:

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

延迟调用函数直到当前调用堆栈已清除,类似于使用延迟为0的setTimeout.

所以你也可以这样做:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我的天啊.我完全不相信这是有效的. (3认同)
  • @DanielAranda:但这会迫使调用者了解视图的实现细节,并根据您的视图进行非标准的操作.所以这是一个你想要哪种kludge(或者在当地情况下哪种可能)的问题. (2认同)

Xes*_*ued 26

我知道这已经回答了,但我想我会分享.使用_.defer函数为您提供了下划线js.

render: function() {
    $(this.el).html(this.template({title: 'test'}));  //#1
    _.defer( function( view ){ view.renderScatterChart();}, this );
    return this;
},
Run Code Online (Sandbox Code Playgroud)

根据Underscore的文档,这与公认的解决方案实际上是一回事.