Last Updated: February 25, 2016
· msdark

Backbonejs events in CollectionView or ItemView

What approach would be more efficient?

I have a Backbone.Collection so i Create a Backbone.View to render this collection. The CollectionView render method:

render: ->
    container = document.createDocumentFragment()
    @collection.each (item) ->
        view = new ItemView(item)
        container.appendChild view.el
    $(el).append container

I can use the events in two forms.

1.- Set the events object in CollectionView, so i need to declare the action of select an item in the CollectionView and "rescue" the model that i selected.

CollectionView extends Backbone.View
        'click #itemView', 'onSelectItem'
    onSelectItem: ->
        ##Get the model
        ##Show ItemDetailView

2.- Set the events object per itemView, so the select method don't need to retrieve the model.

ItemView extends Backbone.View
        'click #div','onSelect'
    onSelect: ->
        #Show ItemDetailView

Which of this options are better?

JSperf snippet to test this

JSperf show us that the ItemView approach have a better performance and is more "intuitive" use items events in each ItemView.

1 Response
Add your response

Check out Marionette. It's got a CollectionView and an ItemView built-in (among other useful tools)

over 1 year ago ·