A Backbone.js Playground
A simple playground for learning backbone.js without having to install or configure anything yourself.
by secretgspot
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script src="https://raw.github.com/mikeric/rivets/master/lib/rivets.js"></script>
<script id='item' type='text/template'>
<li>
<input type='checkbox' data-checked='item.fluctuate' />
<span class='name' data-text='item.name | capitalize'></span>
<span class='price' data-text='item.price | money'></span>
<span class='fluctuating' data-show='item.fluctuate'>fluctuating</span>
</li>
</script>
<a href='javascript:void(0);' class='toggle'>toggle all</a>
<ul></ul>
CSS
li {
margin: 4px 0;
}
.price {
font-family: monospace;
}
.name {
margin: 0 4px;
}
.fluctuating {
margin-left: 6px;
font-size: 10px;
color: #999;
}
CoffeeScript
rivets.configure
preloadData: true
adapter:
subscribe: ( obj, keypath, callback ) ->
callback.wrapped = (m, v) -> callback(v)
obj.on "change:#{keypath}", callback.wrapped
unsubscribe: ( obj, keypath, callback ) ->
obj.off "change:#{keypath}", callback.wrapped
read: ( obj, keypath ) ->
obj.get( keypath )
publish: ( obj, keypath, value ) ->
obj.set( keypath, value )
formatters:
capitalize: ( v ) ->
"#{v[0].toUpperCase()}#{v.slice(1)}"
money: ( v ) ->
"$#{(v / 100).toFixed(2)}"
class Item extends Backbone.Model
defaults: () ->
fluctuate: false
price: 0
toggle: () -> this.set( fluctuate: !this.get('fluctuate') )
class ItemView extends Backbone.View
render: () ->
@setElement $('#item').html()
rivets.bind( @el, item: @model )
@
$(document).ready () ->
container = $('ul:first')
items = new Backbone.Collection( [] )
while (i ?= 1) <= 20
item = new Item( name: "item #{i++}" )
f = ( m ) ->
() ->
if m.get('fluctuate')
m.set( price: Math.floor(Math.random() * 2000) )
setInterval f(item), 750
items.add item
view = new ItemView( model: item )
container.append view.render().el
$('a.toggle').click () -> items.invoke('toggle')