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

前端 未结 7 1428
天命终不由人
天命终不由人 2020-11-29 05:48

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

相关标签:
7条回答
  • 2020-11-29 06:14

    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")
    },
    
    0 讨论(0)
  • 2020-11-29 06:15
     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/

    0 讨论(0)
  • 2020-11-29 06:20

    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'); 
        } 
    });
    
    0 讨论(0)
  • 2020-11-29 06:22

    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.

    0 讨论(0)
  • 2020-11-29 06:28

    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.

    0 讨论(0)
  • 2020-11-29 06:31

    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.

    0 讨论(0)
提交回复
热议问题