Created
August 2, 2013 08:01
-
-
Save cnych/6138214 to your computer and use it in GitHub Desktop.
Backbone入门教程
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function(){ | |
var Item = Backbone.Model.extend({ | |
defaults: { | |
part1: 'hello', | |
part2: 'world' | |
} | |
}) ; | |
var List = Backbone.Collection.extend({ | |
model: Item | |
}) ; | |
var ItemView = Backbone.View.extend({ | |
tagName: 'li', | |
initialize: function(){ | |
_.bindAll(this, 'render') ; | |
}, | |
render: function(){ | |
$(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>') ; | |
} | |
}) ; | |
var ListView = Backbone.View.extend({ | |
el: $('body'), | |
events: { | |
'click button#add': 'addItem' | |
}, | |
initialize: function(){ | |
//every function that users 'this' as the current object should be in here | |
_.bindAll(this, 'render', 'addItem', 'appendItem') ; | |
this.collection = new List() ; | |
this.collection.bind('add', this.appendItem) ; | |
this.counter = 0 ; | |
this.render() ; | |
}, | |
render: function(){ | |
var self = this ; | |
$(this.el).append("<button id='add'>Add list item</button>") ; | |
$(this.el).append("<ul></ul>") ; | |
_(this.collection.models).each(function(item){ | |
self.appendItem(item) ; | |
}, this) ; | |
}, | |
addItem: function() { | |
this.counter++ ; | |
var item = new Item() ; | |
item.set({ | |
part2: item.get('part2') + this.counter | |
}) ; | |
this.collection.add(item) ; | |
}, | |
appendItem: function(item){ | |
$('ul', this.el).append("<li>"+item.get('part1')+" "+item.get('part2')+"</li>") ; | |
} | |
}) ; | |
var listView = new ListView() ; | |
}) ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment