script.coffee | |
---|---|
Using a Collection of Models | |
So far we've used the view as our view and model. We'll extend Backbone.Model and Backbone.Collection to separate our model from our view. | |
You might want to wiew the implementation of this step before diving in. | |
jQuery ->
| |
The model is the heart of any application. We have a very small heart in this example. | class Item extends Backbone.Model
|
| defaults:
part1: 'Hello'
part2: 'Backbone'
|
Our collection is
an ordered set of the previously defined | class List extends Backbone.Collection
model: Item
class ListView extends Backbone.View
el: $ 'body'
|
| initialize: ->
_.bindAll @
@collection = new List
@collection.bind 'add', @appendItem
@counter = 0
@render()
render: ->
$(@el).append '<button>Add List Item</button>'
$(@el).append '<ul></ul>'
|
| addItem: ->
@counter++
|
Instantiate a new Item, | item = new Item |
and modify its second part. | item.set part2: "#{item.get 'part2'} #{@counter}" |
Then, add it to our collection. | @collection.add item
|
| appendItem: (item) ->
$('ul').append "<li>#{item.get 'part1'} #{item.get 'part2'}!</li>"
events: 'click button': 'addItem'
list_view = new ListView |
Onward to Part 4. | |