Skip to content

Instantly share code, notes, and snippets.

@ruzzbot
Created March 12, 2012 20:07
Show Gist options
  • Save ruzzbot/2024378 to your computer and use it in GitHub Desktop.
Save ruzzbot/2024378 to your computer and use it in GitHub Desktop.
javascript: backbone-list
//=== LIST
Article.Views.List = Backbone.View.extend({
template: "",
initialize: function( options ){
_.bindAll(this, "render", "addAll", "addOne");
this.collection.bind( "add", this.addOne );
this.collection.bind( "reset", this.addAll );
this.totalItems = this.collection.length;
},
render: function( done ) { this.addAll( done ); },
addAll: function( done ){
var view = this;
this.el.innerHTML = "";
onRenderComplete = null;
//loop through items, and pass render-complete function to item to call on list loop
this.collection.each( function( model, i ){
if( i+1 === view.totalItems )
onRenderComplete = done;
view.addOne( model, done );
});
},
addOne: function( model, done ){
var view = this;
var li = new Article.Views.ListItem({
model: model,
template: view.options.li_template
});
li.render( function( el ){
view.$el.append( el );
if( _.isFunction( done ) )
done( view.el );
});
model.bind("remove", li.remove);
}
});
//=== LIST ITEM VIEW
Article.Views.ListItem = Backbone.View.extend({
template : "List-Item-Placeholder",
className : "list-item",
initialize: function( options ){
if( options.template )
this.template = options.template
if( options.className )
this.template = options.className
if( options.tagName )
this.tagName = options.tagName
},
render: function(done) {
var view = this;
var model = this.model;
// Fetch the template, render it to the View element and call done.
revlon.fetchTemplate(this.template, function(tmpl) {
view.el.innerHTML = tmpl( model.toJSON() );
// If a done function is passed, call it with the element
if (_.isFunction(done)) {
done(view.el);
}
});
};
});
//======= EXAMPLE IMPLEMENTATION =======/
var fetch_success = function( d ){
var view = new Article.Views.RecentActivity({
collection: d,
template : '/app/templates/list.html',
listItem : {
className : "list-item",
template :'/app/templates/listItem.html',
}
});
view.render( function(el){
console.log( 'Render complete' );
$( 'body' ).html( el );
});
};
//init after success
var collection = new Article.Collection();
collection.fetch({ success: fetch_success });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment