Skip to content

Instantly share code, notes, and snippets.

@hapticdata
Last active August 29, 2015 14:10
Show Gist options
  • Save hapticdata/c501e5e4cc7c80f08201 to your computer and use it in GitHub Desktop.
Save hapticdata/c501e5e4cc7c80f08201 to your computer and use it in GitHub Desktop.
A Backbone View container, using Q for promises. Expects children with a `transitionIn` and `transitionOut` function that return promises.
define(function( require, exports, module ){
var _ = require('underscore'),
Backbone = require('backbone'),
Q = require('q');
/**
* This is a generic view that manages additional children views
* use `addChild` and `removeChild` to nest a view within
*/
var View = Backbone.View.extend({
initialize: function( opts ){
_.bindAll(this, 'remove', 'removeChild','transitionIn', 'transitionOut', 'render');
this.children = [];
this.options = opts || {};
},
/**
* add a child to the view
* @param {Backbone.View} view the view to add.
*/
addChild: function( view ){
this.children.push(view);
this.trigger('add', view);
},
/**
* remove a child from the view
* @param {Backbone.View} view the view to remove.
* @return {Boolean} true if the view was removed
*/
removeChild: function( view ){
if( _.contains(this.children, view) ){
view.remove();
this.children = _.without(this.children, view);
this.trigger('remove', view);
return true;
}
return false;
},
remove: function(){
_.each(this.children, this.removeChild);
return Backbone.View.prototype.remove.call(this);
},
render: function(){
_.invoke(this.children,'render');
_.each(this.children, function(c){ this.append(c.$el); }, this.$el);
return this;
},
transitionIn: function( opts ){
//simultaneously call transitionIn on all elements,
//resolve promise when all are done
return Q.all(_.invoke(this.children, 'transitionIn', opts));
},
transitionOut: function(){
//simultaneously call transitionOut on all elements,
//resolve promise when all are done
return Q.all(_.invoke(this.children,'transitionOut'))
.done(this.remove, this.remove);
}
});
return View;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment