Backbone, trigger an events when all is loaded

别等时光非礼了梦想. 提交于 2020-01-01 17:11:40

问题


In my backbone app I load 3 Collections and I bind the "reset" event at the render function. So, in this way, when I fetch the Collections, I print the various results, but not simultaneously.

I would use the jquery deferred methods ($.when, $.then) to print all simultaneously, how to do this if I use the "bind events" on the views?

this is the code:

Router:

App.Routers.test1 = Backbone.Router.extend({  

    routes: {       
        "/test" : "test"        
    },

    initialize: function() {                            
        // Models
        this.Models_1 =     new App.Collections.coll_1;     
        this.Models_2 =     new App.Collections.coll_2;
        this.Models_3 =     new App.Collections.coll_3;

        // Views
        this.View_1 =       new App.Views.view_1( {model: this.Models_1} );
        this.View_2 =       new App.Views.view_2( {model: this.Models_2} );
        this.View_3 =       new App.Views.view_3( {model: this.Models_3} );         
    },

    test: function() { 
        $.when(

            this.Models_1.fetch(),
            this.Models_2.fetch(),
            this.Models_3.fetch()

        ).then(function() {

            // ?????????????????????????

            //  What should I do here?

            // ?????????????????????????

        });
    }

});

View 1:

App.Views.view_1 = Backbone.View.extend({

    initialize: function() {
        _.bindAll(this, 'render');
        this.model.bind('reset', this.render);
    },

    render: function() {

        // print the data...

    }

}); 

回答1:


test: function() { 
    $.when(
        this.Models_1.fetch({silent: YES}), // silent will prevent triggering any events on reset or add
        this.Models_2.fetch({silent: YES}),
        this.Models_3.fetch({silent: YES})
    ).then(_.bind(function() {
        this.Models_1.trigger('reset'); // manually trigger events in sequence you want
        this.Models_3.trigger('reset');
        this.Models_2.trigger('reset');
    }, this));
}



回答2:


Not sure where you are going with your deferred events. Backbone already has a way to do this.

In your view, bind the event "refresh" from the collection to the view render function. Whenever you will call fetch on the collection, the refresh event will be triggered and your view rerendered.




回答3:


Perhaps underscores defer is the method you're looking for?

Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating.



来源:https://stackoverflow.com/questions/7150533/backbone-trigger-an-events-when-all-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!