能夠查看http://www.css88.com/doc/backbone/javascript
backbone與angular http://www.infoq.com/cn/articles/backbone-vs-angular/css
http://blog.csdn.net/huangxin0102/article/details/50930772html
1.java
/** * 模型 - Model */ var Note = Backbone.Model.extend({ defaults: { title: '', created_at: new Date() }, initialize: function() { console.log('新建立了一條筆記:' + this.get('title')); this.on('change', function(model, options) { console.log('屬性的值發生了變化'); }); this.on('change:title', function(model, options) { console.log('title 屬性發生了變化'); }); this.on('invalid', function(model, error) { console.log(error); }) }, validate: function(attributes, options) { if (attributes.title.length < 3) { return '筆記的標題字符數要大於 3'; } } }); /** * 視圖 - View */ var NoteView = Backbone.View.extend({ tagName: 'li', className: 'item', attributes: { 'data-role': 'list' }, template: _.template(jQuery('#list-template').html()), render: function() { this.$el.html(this.template(this.model.attributes)); return this; } }); /** * 集合 - Collection */ var NoteCollection = Backbone.Collection.extend({ model: Note, initialize: function() { this.on({ 'add': function(model, collection, options) { console.log('ID: ' + model.id + '模型添加到了集合裏'); }, 'remove': function(model, collection, options) { console.log('ID: ' + model.id + '模型從集合裏刪除掉了'); }, 'change': function(model, options) { console.log('集合裏的模型發生了變化'); } }); } }); //學習到的 /** * var ss = new NoteCollection(); ss.add({id: 4, title: '西紅柿炒雞蛋的作法'});//能夠這樣子新添加一個 ss.add({id: 4, title: '西紅柿炒雞蛋的作法'},{merge:true}); 還有remove,reset,pop,shift set方法能夠設置remove:false的 */ /** * 集合視圖 - Collection View */ var NoteCollectionView = Backbone.View.extend({ tagName: 'ul', initialize: function() { this.collection.on('add', this.addOne, this); this.render(); }, render: function() { this.collection.each(this.addOne, this); return this; }, addOne: function(note) { var noteView = new NoteView({model: note}); this.$el.append(noteView.render().el); } }); /** * 測試 */ var note1 = new Note({id: 1, title: '西紅柿炒雞蛋的作法'}); var note2 = new Note({id: 2, title: '週六參加朋友的婚禮'}); var note3 = new Note({id: 3, title: '晚上回家洗尿布'}); var noteCollection = new NoteCollection([note1, note2, note3]); var noteCollectionView = new NoteCollectionView({collection: noteCollection});
backbone的路由app
var NoteRouter = Backbone.Router.extend({ routes: { 'notes': 'index', 'notes/:id': 'show', 'login(/from/*from)':'login'//*表示不論後邊有多少層路由 }, index: function() { jQuery('#note_list').html(noteCollectionView.el); console.log('筆記列表'); }, show: function(id) { this.navigate('login/from/notes/'+id,{trigger,true});//trigger true表示能夠出發方法 console.log('筆記:' + id); var note = noteCollection.get(id); var noteView = new NoteView({model: note}); jQuery('#note_list').html(noteView.render().el); } }); var noteRoute = new NoteRouter; Backbone.history.start();