Last Updated: February 25, 2016
·
2.644K
· 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
        view.render()
    $(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
    events:
        '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
    events:
        'click #div','onSelect'
    onSelect: ->
        #Show ItemDetailView

Which of this options are better?

JSperf snippet http://jsperf.com/backbone-events-on-collectionview-or-per-itemview 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside