Reputation: 2415
In the below code block I need to make sure initialize1
and initialize2
calls to the remoteAPIObj
are both finished before rendering my view. Both functions are doing AJAX queries and execute the given callback functions.
So I have defined another function renderOnce
and used underscore.js function after
to make sure renderOnce
is actually called 2 times before actually being executed. Is there anything missing in this approach? Or do you have any other suggestion?
window.MyView = Backbone.View.extend({
el: $('#right-container'),
render: function(eventName) {
var template = Handlebars.compile($("#right-template").html());
$(this.el).html(template(remoteAPIObj.getData()));
return this;
},
initialize: _.once(function() {
var self = this;
remoteAPIObj.initialize1(function(){self.renderOnce();});
remoteAPIObj.initialize2(function(){self.renderOnce();});
}),
renderOnce: _.after(2, function() {
this.render();
})
});
Upvotes: 1
Views: 2344
Reputation: 50029
The ideal way to do this with a jQuery promises approach - http://api.jquery.com/jQuery.when/
Example :
$.when( $.ajax("test.aspx") ).then(function(ajaxArgs){
alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});
If your internal code can be adapted to promises, you can do something like this
$.when(remoteAPIObj.initialize1, remoteAPIObj.initialize2).then(function(args1, args2){
this.render();
});
Failing that, you can also use the event system to trigger an event that notifies the render method that the data is available. But this won't be terribly different than what you are already doing.
Upvotes: 1