Skip to content

Instantly share code, notes, and snippets.

@praxxis
Last active December 20, 2015 15:49
Show Gist options
  • Save praxxis/6157326 to your computer and use it in GitHub Desktop.
Save praxxis/6157326 to your computer and use it in GitHub Desktop.
An implementation of a "promise region" for Backbone.Marionette. Lets you easily create and manage "loading" views, that are eventually replaced by a view with content.
var LoadingView = Backbone.Marionette.ItemView.extend({
template: 'Loading...'
});
var LoadedView = Backbone.Marionette.ItemView.extend({
template: 'Loaded!'
});
var View = Backbone.Marionette.Layout.extend({
template: '<div class="example"></div>',
initialize: function () {
// note that there's a bug with Backbone.Marionette.Layout that means you can't set the regionType for all regions:
// https://github.com/marionettejs/backbone.marionette/issues/674
this.addRegion('exampleRegion', {
selector: '.example',
regionType: PromiseRegion
})
var promise,
dfd = $.Deferred();
setTimeout(function () {
dfd.resolve(new LoadedView());
}, 3000));
promise = dfd.promise();
// will show "Loading..." then three seconds later, replace it with "Loaded!"
// view management (unbinding events, etc) is completely handled by Marionette
this.exampleRegion.show(new LoadingView());
this.exampleRegion.show(promise);
}
})
var PromiseRegion = Backbone.Marionette.Region.extend({
show: function (ViewOrPromise) {
var self = this,
show = Backbone.Marionette.Region.prototype.show;
if (typeof ViewOrPromise.then === 'function') {
ViewOrPromise.done(function (View) {
show.call(self, View);
});
} else {
show.call(this, ViewOrPromise);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment