calling javascript on rendering views in BackBone js. post-render callback?

后端 未结 8 1643
粉色の甜心
粉色の甜心 2020-12-04 19:55

behold, a backbone view render call:

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


        
8条回答
  •  攒了一身酷
    2020-12-04 20:35

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

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

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

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

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

    So you could also do it like this:

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

提交回复
热议问题