backbone_Collection的create,add,push,unshift

1. model定义

 

var app = app || {};

(function () {
    'use strict';

    // User Model
    // ----------

    
    app.User = Backbone.Model.extend({
        
        defaults: {
            firstName: '',
            lastName: '',
            telNo:'',
            email:''
        },

    });
})();

 

2.Collection定义

var app = app || {};

(function () {
    'use strict';


    var Users = Backbone.Collection.extend({
        // Reference to this collection's model.
        model: app.User,

        // Save all of the todo items under the `"todos"` namespace.
        localStorage: new Backbone.LocalStorage('users-backbone'),
        
        

    });

    // Create our global collection of **Users**.
    app.users = new Users();
})();

 

3. View

/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
    'use strict';

    
    app.AppView = Backbone.View.extend({
        
        //el: '.user-list-tb',
        el: '.container',
        
        events: {
            'click #register-btn': 'register',
            'click #add-btn': 'add',
            'click #push-btn': 'push',
            'click #unshift-btn': 'unshift',
            //'click #add': 'register',
        },

        initialize: function() {
            this.$list = $('#user-list-bd');
            //this.$list = $('#user-list');
            
            this.listenTo(app.users, 'add', this.addOne);
            this.listenTo(app.users, 'reset', this.addAll);
            //this.listenTo(app.users, 'all', _.debounce(this.render, 0));
            
            app.users.fetch({reset: true});
        },

        /*render: function() {
            
        },*/
        
        newAttributes: function() {
            return {
                firstName:this.$("#firstname").val(),
                lastName:this.$("#lastname").val(),
                telNo:this.$("#telNo").val(),
                email:this.$("#email").val(),
            };
        },
        
        register: function() {

            var a = this.newAttributes();
            app.users.create(a);
            
        },
        
        addOne: function(user) {
            var view = new app.UserlistView({ model: user });
            this.$list.append(view.render().el);
            //$('#aa').append("<span>bb</span>");
        
        },
        
        addAll: function() {
            ///this.$list.html('');
            app.users.each(this.addOne, this);
        
        },
        
        add: function(){
            var a = this.newAttributes();
            app.users.add(a,{at:2});
            console.dir(app.users);
        },
        
        push: function(){
            var a = this.newAttributes();
            app.users.push(a);
            console.dir(app.users.models);
        },
        
        unshift: function(){
            var a = this.newAttributes();
            app.users.unshift(a);
            console.dir(app.users);
        }
        
    });
})(jQuery);
/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
    'use strict';

    
    app.UserlistView = Backbone.View.extend({
        tagName:  'tr',
        //tagName:  'li',
        
        template: _.template($('#user-list').html()),
        //template: _.template('<div><%= firstName %>:<%= telNo %></div>'),
        
        initialize: function () {

            this.listenTo(this.model, 'change', this.render);
        },

        // Re-render the titles of the todo item.
        render: function () {

            /*if (this.model.changed.id !== undefined) {
                return;
            }

            this.$el.html(this.template(this.model.toJSON()));
            this.$el.toggleClass('completed', this.model.get('completed'));
            this.toggleVisible();
            this.$input = this.$('.edit');
            return this;*/
            var a = this.template(this.model.toJSON());
            this.$el.html(a);
            return this;
        },
        
    });
})(jQuery);

 

4. create,add,push,unshift

首先看下create的源代码

    // Create a new instance of a model in this collection. Add the model to the
    // collection immediately, unless `wait: true` is passed, in which case we
    // wait for the server to agree.
    create: function(model, options) {
      options = options ? _.clone(options) : {};
      var wait = options.wait;
      if (!(model = this._prepareModel(model, options))) return false;
      if (!wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(model, resp, callbackOpts) {
        if (wait) collection.add(model, callbackOpts);
        if (success) success.call(callbackOpts.context, model, resp, callbackOpts);
      };
      model.save(null, options);
      return model;
    },

 

从源代码来看,create调用model的add方法,然后又调用了save方法,save方法将保存模型到数据库(或替代持久化层)。

create方法触发collection的add事件和sync事件。

 

再看下add,push,unshift的源代码

// Add a model, or list of models to the set.
add: function(models, options) {
      return this.set(models, _.extend({merge: false}, options, addOptions));
    },
    
// Add a model to the end of the collection.
    push: function(model, options) {
      return this.add(model, _.extend({at: this.length}, options));
    
    },
    
    unshift: function(model, options) {
      return this.add(model, _.extend({at: 0}, options));
    },

 

add方法是向集合中增加一个模型(或一个模型数组),触发"add"事件。

传递{at: index}可以将模型插入集合中特定的index索引位置。

push是向集合的末尾增加一个模型。

而unshift是向集合的头上追加一个模型。

当然我们调用的时候,还可以指定option,比如{at: 2}来更改插入位置。

从上面的源代码可以看出,上面3个函数归根结底都是调用set函数,并没有调用save,所以不会将新增加的模型保存到服务器。

 

5. 关于set方法

http://www.css88.com/doc/backbone/#Collection-set

上是这样解释的:

set方法通过传递模型列表执行一个集合的"smart(智能)"的更新。 如果列表中的一个模型尚不在集合中,那么它将被添加; 如果模型已经在集合中,其属性将被合并; 并且如果集合包含存在于列表中的任何模型,他们将被删除。 以上所有将触发相应的"add", "remove", 和 "change"事件。 返回集合中的模型。 如果您想自定义的行为, 你可以设置选项:{add: false}, {remove: false}, 或 {merge: false},将其禁用。

 

转载于:https://www.cnblogs.com/alicewang999/p/4648527.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值