backbone.cocomp demo

Demonstrates how to use backbone.cocomp to compare the contents of two lists, and update the view, using events

by David Biehl

HTML

<script src="https://rawgithub.com/davidbiehl/backbone.cocomp/master/spec/lib/underscore-min.js"></script>
<script src="https://rawgithub.com/davidbiehl/backbone.cocomp/master/spec/lib/backbone-min.js"></script>
<script src="https://rawgithub.com/davidbiehl/backbone.cocomp/master/backbone.cocomp.js"></script>
Click on a name in box1 to add the model to box2.
<br />Click on a name in box2 to remove it from box 2.
<br/>Box1 is only listening to cocomp events to affect the view.

<h2>Box 1</h2>

<ul id="box1"></ul>

<h2>Box 2</h2>

<ul id="box2"></ul>

SCSS

.selected {
    font-weight: bold;
    text-decoration: line-through;
}

CoffeeScript

# Setup some boxes

box1 = new Backbone.Collection([
    {id: 1, name: "John Doe"},
    {id: 2, name: "Alfred"},
    {id: 3, name: "Shoeless Mike"}
])
box2 = new Backbone.Collection()

# A very generic List view
List = Backbone.View.extend
    initialize: (options)->
        @listenTo @collection, 'add remove reset', @render
        @itemView = options.itemView
    render: ->
        @$el.empty()
        @collection.forEach (item)=>
            @renderOne(item)
    renderOne: (item)->
        item = new @itemView(model: item)
        item.render()
        @$el.append(item.el)

# An Item view for the models in Box1
#
# The onClick only adds the model to box2
#
# The state of the UI is changed with the
# cocomp events
Box1Item = Backbone.View.extend
    tagName: 'li'
    events:
        'click': 'onClick'
    initialize: ->
        @listenTo @model, 'cocomp:in:box2', @onInBox2
        @listenTo @model, 'cocomp:out:box2', @onOutBox2
    render: ->
        @$el.html(@model.get('name'))
    onClick: ->
        box2.add(@model)
    onInBox2: ->
        @$el.addClass('selected')
    onOutBox2: ->
        @$el.removeClass('selected')
        
        
# An item view for the models in box2
#
# All the onClick does is remove the model
# from box2
Box2Item = Backbone.View.extend
    tagName: 'li'
    events:
        'click': 'onClick'
    initialize: ->
        @listenTo @model, 'remove', @remove
    render: ->
        @$el.html(@model.get('name'))  
    onClick: ->
        box2.remove(@model)

# Instanciate and render the list views
list1 = new List(collection: box1, el: $('#box1'), itemView: Box1Item)
list2 = new List(collection: box2, el: $('#box2'), itemView: Box2Item)

list1.render()
list2.render()

# Create a new CoComp and set the collections
# Watch the magic happen!
cocomp = new Backbone.CoComp
        
cocomp.set "box1", box1
cocomp.set "box2", box2