I am using a technique I read about from Sam Breed for using Deferreds inside of Backbone.
Inside my initialize method of my Backbone View I have the following:
var me = this;
this.deferredTemplate = $.ajax({
url: 'details/welcomeMaster.htm'
}).done(function (data) {
me.template = data;
});
This will load a template file for me that is located externally to my View.
Then when I need it here is the code to new it up.
var something = new Dashboard.Views.WelcomeMasterView({
collection: me.collection,
el: $('.contentContainer')
});
something.deferredTemplate.done(function (data) {
something.render();
});
Unfortunately I have to break up those 2 statements so that something is my Backbone View and not the jqXHR object. Other than that this code works just fine.
Question
Any ideas on how to chain together the 2 calls above? Inside the .done() method I need the Backbone View object.
I think if you want to keep it simple you might prefer to first load the templates, then construct any views once you have fetched them. This is say how things work with AMD loaders providing the same thing.
Otherwise, one idea would be to add a
_renderthat would do what yourrendernormally does, sayThen, your normal
renderwould call_renderwhen ready:This would keep things simple and you can go on calling
render()the same way you always do. Note however the drawback: If you rely on having actually rendered after a call to render (say for instance you manipulate the$elsomewhere else), you might not actually have the element there.As a side note, while deferreds are a perfect fit for Backbone, their usage in the blog post you link to is unnecessary. A simple bind to
changewould have accomplished the same task in a cleaner way.