Backbone入门基础 - 集合

本文介绍了Backbone.js集合的基本用法,包括实例化、查询、遍历等操作方法,并详细解析了find、filter及where等函数的使用技巧。同时,还提供了add、remove等常用方法的具体应用案例。

集合基本用法

[1] 基类Collection

1)实例化、初始化
var list=[
    {
        title: 'title1',
        description: 'des1'
    },
    {
        title: 'title2',
        description: 'des2'
    },
    {
        title: 'title3',
        description: 'des3'
    }
];
var MyList=Backbone.Collection.extend({
});
var aList= new MyList(list);
2)models数组
  • 集合是管理backbone对象,不是原生的对象。
    这里写图片描述
3)toJSON
  • 把Backbone对象,打回到JS的原生对象
    这里写图片描述
4)length/size
  • 以下几种方式都可以获得collection长度,size()是underscore的方法。
    这里写图片描述

[2] 查询 find/filter/where

1)find
  • 在集合中遍历找到一个元素。
  • 条件是以回调函数的方式来实现。find内部对集合有个迭代,并且每次迭代都调用回调方法。所以回调方法需要告诉迭代器,当前model是否满足查询条件。
var foo=aList.find(function(model){
    return model.get('title') == 'title1';
});

这里写图片描述

2)filter
  • 在集合中遍历找到多个元素。
var foo=aList.filter(function(model){
return model.get('description') == 'des1';
});

这里写图片描述
注意:集合提供的filter方法返回的是一个JS的原生数组,而非集合

3)where
  • 是find和filter的快捷写法。
//相当于filter,不用写回调函数,只需要传目标属性参数对
var foo1=aList.where({
    description : 'des1'
});
//相当于find,第二个参数为true,只查找一个参数
var foo2=aList.where({
    description : 'des1'
},true);
4)Backbone.QueryCollection

[3] 遍历 each

aList.each(function(model){
    console.log(model.get('title'));
});

[4] 其他方法

1)every
//是否每个都满足条件,foo_every为布尔型
var foo_every=aList.every(function(model){
   return model.get('title') != null;
});
2)some
//只要有一个满足条件返回true,foo_some为布尔型
var foo_some=aList.some(function(model){
    return model.get('title') != null;
});
3)pluck
//摘取某个属性,组成新的JS数组
var foo_pluck=aList.pluck('title’);

这里写图片描述

4)map
//遍历model,自定义内容,组成新数组
var foo_map=aList.map(function(model){
    return model.get('title') +' '+ model.get('description');
});

这里写图片描述

5)reduce
//将集合中的内容变为一个值。memo表示上一次的结果,reduce的第二个参数代表初始值
var foo_map=aList.reduce(function(memo,model,index){
    return memo + ',' + model.get('title');
},'');

这里写图片描述

集合事件

补充内容:
(1) cid是model内部的唯一ID
(2) Undercore的_.each()方法
    _.each(list, iterator, [context])
    list是要循环迭代的集合,iterator是迭代器,context是迭代器的上下文,也就是迭代器中this的指向,例如: 
var obj = {name: "hello"};  
_.each([1, 2, 3], function (i) { 
  console.log(this.name + ":" + i); 
}, obj); 
//--result--
hello:1 
hello:2 
hello:3 
[1] add (可指定插入位置)
[2] remove
[3] reset
[4] sort (comparetor设置)
  • 以上方法用实例展示
    这里写图片描述
<ul id="aView">
</ul>
var list=[
    {
        title: 'atitle1',
        description: 'des1'
    },
    {
        title: 'ctitle2',
        description: 'des2'
    },
    {
        title: 'btitle3',
        description: 'des1'
    }
];
var MyList=Backbone.Collection.extend({
    //-直接通过某个字段的ASCII排序-
    //comparator: 'title'
    //-复杂排序-
    comparator: function(a,b){
        return a.get('title').length > b.get('title').length
    }
});
var aList= new MyList(list);
var ItemView = Backbone.View.extend({
    tagName: 'li',
    className: 'list-item',
    render:function(){
        this.$el.html(this.model.get('title'));
        return this;
    }
});
var ListView = Backbone.View.extend({
    initialize: function(){
        if(this.collection){
            this.byId ={};
            this.views=[];
            this.collection.each(this.registerView,this);
            this.listenTo(this.collection,'reset',this.resetView);
            this.listenTo(this.collection,'add',this.addView);
            this.listenTo(this.collection,'remove',this.removeview);
            this.listenTo(this.collection,'change',this.updateView);
            this.listenTo(this.collection,'sort',this.resetView);
        }
    },
    registerView: function(model) {
        var view = new ItemView({model: model});
        this.byId[model.cid] = view;
        this.views.push(view);
    },
    addView: function(model){
        var view = new ItemView({model:model});
        var at = this.collection.indexOf(model);
        this.byId[model.cid] = view;
        $before = this.views[at-1].$el;
        $before.after(view.render().$el);
        this.views.splice(at,0,view);
    },
    resetView:function(){
        this.byId={};
        this.views=[];
        this.collection.each(this.registerView,this);
        this.render();
    },
    updateView: function(model){
        var view = this.byId[model.cid];
        view.render();
    },
    render:function(){
        var _this= this;
        this.$el.empty();
        _.each(this.views,function(view){
            $_el = view.render().$el;
            _this.$el.append($_el);
        });
        return this;
    }
});
var aView= new ListView({
    el:'#aView',
    collection: aList
});
aView.render();
//--add--
aList.add({
    title : 'title added',
    description: 'des added'
},{at: 2});
var newDataSource = [
    {
        title: 'new_title1',
        description: 'des1'
    },
    {
        title: 'new_title2',
        description: 'des2'
    },
    {
        title: 'new_title3',
        description: 'des1'
    }
];

集合与服务器交互

<ul id="aView">
</ul>
var MyItem = Backbone.Model.extend();
var MyItemView = Backbone.View.extend({
    tagName: 'li',
    render: function(){
        this.$el.html(this.model.get('title'));
        return this;
    }
});
var MyCollection = Backbone.Collection.extend({
    url: 'js/package.json',
    model: MyItem
});
var MyCollectionView = Backbone.View.extend({
    initialize: function(){
        this.listenTo(this.collection,'reset',this.render);
        this.views=[];
    },
    render: function(){
        var that= this;
        _.each(this.views,function(view){
            view.remove();
        }),
        this.collection.each(function(model){
            var view= new MyItemView({model: model});
            that.views.push(view);
            that.$el.append(view.render().$el);
        });
    }
});
var myCollection = new MyCollection();
var myCollectionView=new MyCollectionView({
    collection: myCollection,
    el: '#aView'
});
myCollection.fetch({reset:true});

注:下图1可以实现功能,当时,会造成内存泄露,所以改为图2红框内容。
这里写图片描述

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值