1.
/** * 模型 - 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});
时间: 2024-10-19 18:12:50