在 BackBone js 中调用 javascript 渲染视图.渲染后回调? [英] calling javascript on rendering views in BackBone js. post-render callback?

查看:21
本文介绍了在 BackBone js 中调用 javascript 渲染视图.渲染后回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看,一个主干视图渲染调用:

behold, a backbone view render call:

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

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

so, I call a standard render at #1. and then, i call a method [this time, it is a wrapper for charting lib] that looks for a div. the div is rendered by the render call. but at this point, it is not attached to the DOM yet (right?). so the chart call sadly dies.

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

what is the pattern for this? i'd love hear that there is a post-render callback. i've tried a few hacks around this, and sometimes i get the chart to work, but events don't bind.

推荐答案

对于这类事情,我通常的做法是使用 setTimeout 超时为零,以安排浏览器再次获得控制权后发生的事情.试试这个:

My usual approach for this sort of thing is to use setTimeout with a timeout of zero to arrange for something to happen once the browser gets control again. Try this:

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

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

    return this;
}

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

Or, if renderScatterChart is already bound to the appropriate this:

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

如果你想更明确,你也可以使用 _.defer关于你在做什么:

You can also use _.defer if you want to be more explicit about what you're up to:

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

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

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;
}

这篇关于在 BackBone js 中调用 javascript 渲染视图.渲染后回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆