Backbone.js event after view.render() is finished

2020-01-25 07:37发布

Does anyone know which event is fired after a view is rendered in backbone.js?

标签: backbone.js
6条回答
唯我独甜
2楼-- · 2020-01-25 07:51

I ran into this post which seems interesting

var myView = Backbone.View.extend({ 

    initialize: function(options) { 
        _.bindAll(this, 'beforeRender', 'render', 'afterRender'); 
        var _this = this; 
        this.render = _.wrap(this.render, function(render) { 
            _this.beforeRender(); 
            render(); 
            _this.afterRender(); 
            return _this; 
        }); 
    }, 

    beforeRender: function() { 
       console.log('beforeRender'); 
    }, 

    render: function() { 
        return this; 
    }, 

    afterRender: function() { 
        console.log('afterRender'); 
    } 
});
查看更多
▲ chillily
3楼-- · 2020-01-25 07:54

Instead of adding the eventhandler manually to render on intialization you can also add the event to the 'events' section of your view. See http://backbonejs.org/#View-delegateEvents

e.g.

events: {
   'render': 'afterRender'
}

afterRender: function(e){
    alert("render complete")
},
查看更多
甜甜的少女心
4楼-- · 2020-01-25 07:54
 constructor: function(){
   Backbone.View.call(this, arguments);     
   var oldRender = this.render
   this.render = function(){
      oldRender.call(this)
      // this.model.trigger('xxxxxxxxx')
   }       
 }

like this http://jsfiddle.net/8hQyB/

查看更多
Lonely孤独者°
5楼-- · 2020-01-25 07:56

As far as I know - none is fired. Render function is empty in source code.

The default implementation of render is a no-op

I would recommend just triggering it manually when necessary.

查看更多
混吃等死
6楼-- · 2020-01-25 08:10

If you happen to be using Marionette, Marionette adds show and render events on views. See this StackOverflow question for an example.

On a side note, Marionette adds a lot of other useful features that you might be interested in.

查看更多
戒情不戒烟
7楼-- · 2020-01-25 08:18

Or you can do the following, which is what Backbone code is supposed to look like (Observer pattern, aka pub/sub). This is the way to go:

var myView = Backbone.View.extend({ 
    initialize: function() {  
        this.on('render', this.afterRender);

        this.render();
    },

    render: function () {  
        this.trigger('render');
    },

    afterRender: function () {
    }
});

Edit: this.on('render', 'afterRender'); will not work - because Backbone.Events.on accepts only functions. The .on('event', 'methodName'); magic is made possible by Backbone.View.delegateEvents and as such is only available with DOM events.

查看更多
登录 后发表回答