Skip to content

Instantly share code, notes, and snippets.

@bergie
Created May 30, 2012 12:47
Show Gist options
  • Select an option

  • Save bergie/2836052 to your computer and use it in GitHub Desktop.

Select an option

Save bergie/2836052 to your computer and use it in GitHub Desktop.
Backbone.js Collection View example

This is an example of using a Collection view with Backbone.

@dexity
Copy link

dexity commented Feb 25, 2014

Clean and concise solution! Thanks, man. Table rendering drives me nuts.

@htatche
Copy link

htatche commented Mar 21, 2014

Thanks for those snippets, the switch from Ember to Backbone is not so straight-forward sometimes !

@yattias
Copy link

yattias commented Mar 19, 2015

@bergie - very nice & clean dude. One note though, rendering the whole collection when a person is added/removed may be overkill.

@vitalyisaev2
Copy link

@yattias could you please tell whether there are opportunities to avoid the problem you've mentioned (with Backbone of course)?

@okovpashko
Copy link

@vitalyisaev2 you can create your own listener for collection's 'add' event, which will insert new PeopleItem view in correct place:

onCollectionItemAdd: function ( model, collection ) {
    var  list = this.$( 'list selector' ),
        listItems = list.children(),
        newItem = self._renderListItem( model ),
        newItemPosition = collection.models.indexOf( model );

    if ( newItemPosition > listItems.length - 1 ) {
        newItem.$el.appendTo( list );
    } else {
        newItem.$el.insertBefore( listItems.eq( newItemPosition ) );
    }
}

Then you can add listener for model's 'remove' event in PeopleItem view:

onModelRemove: function() {
    this.remove();
}

@TimothyWrightSoftware
Copy link

Just what I needed. Thanks!

@mveer-agarwal
Copy link

Doesn't this solution have DOM Reflow? Here you are attaching child view html with parent view html, which causes DOM Reflow?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment