问题
I need to spend 1 model and 1 collection in my html template with backbone. But sometimes, html is ready after the model. I have :
var FormUtilisateurView = Backbone.View.extend({
initialize: function(id){
this.listeClient = new ClientsCollection();
this.utilisateur = new UtilisateurModel({ id : id });
},
render: function(){
var that = this;
this.utilisateur.fetch();
this.listeClient.fetch().done(function(){
that.$el.html(FormTemplate({ clients : that.listeClient.models, user : that.utilisateur }));
});
return this;
}
});
Here, only listeClient collection is loaded. I want to be sure my model and collection are loaded before the template.
Thank you in advance
回答1:
You can combine the requests' promises returned by fetch with jquery.when to synchronize your rendering task. Something like:
render: function(){
var that = this, promises = [],
user = this.utilisateur, clients = this.listeClient;
promises.push(user.fetch());
promises.push(clients.fetch());
$.when.apply(null, promises).done(function(){
that.$el.html(FormTemplate({clients: clients.models, user: user}));
});
return this;
}
来源:https://stackoverflow.com/questions/27176171/backbone-view-render-with-multiple-model-fetch