码迷,mamicode.com
首页 > 其他好文 > 详细

backbone点滴

时间:2017-03-06 00:59:20      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:not   attribute   模型   标题   class   pen   on()   集合   backbone   

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});

  

backbone点滴

标签:not   attribute   模型   标题   class   pen   on()   集合   backbone   

原文地址:http://www.cnblogs.com/coding4/p/6507504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!