当前位置: 首页 > 工具软件 > Marionette > 使用案例 >

Marionette官网学习 - CollectionView

甄佐
2023-12-01

1. Marionette.CollectionView

引用官网描述

The CollectionView will loop through all of the models in the specified collection, render each of them using a specified childView, then append the results of the child view’s el to the collection view’s el. By default the CollectionView will maintain a sorted collection’s order in the DOM. This behavior can be disabled by specifying {sort: false} on initialize.

2. CollectionView’s childView

引用官网描述

Specify a childView in your collection view definition. This must be a Backbone view class definition, not an instance. It can be any Backbone.View or be derived from Marionette.View.

<script id="foo-template" type="x-template/underscore">
    Foo template content
</script>

<script id="bar-template" type="x-template/underscore">
    Bar template content
</script>
//--model--
var MyModel = Backbone.Model.extend({
    defaults: {
        isFoo: false
    }
});
var bar = new MyModel();
var foo = new MyModel({
    isFoo: true
});

//--子View--
var FooView = Mn.View.extend({
    template: '#foo-template'
});

var BarView = Mn.View.extend({
    template: '#bar-template'
});

//--Collection view--
var MyCollectionView = Mn.CollectionView.extend({
    collection: new Backbone.Collection(),
    childView: function(item) {
    // Choose which view class to render,
    // depending on the properties of the item model
    if  (item.get('isFoo')) {
        return FooView;
    }
    else {
        return BarView;
    }
}
});

//--实例化并渲染到页面上--
const collectionView = new MyCollectionView();
collectionView.render();
$('body').append(collectionView.$el);

//--渲染子View--
// Renders a FooView
collectionView.collection.add(foo);
// Renders a BarView
collectionView.collection.add(bar);

3. CollectionView’s childViewOptions

childViewOptions中返回的值可以在childView中获取到

引用官网描述

There may be scenarios where you need to pass data from your parent collection view in to each of the childView instances. To do this, provide a childViewOptions definition on your collection view as an object literal. This will be passed to the constructor of your childView as part of the options.

var myCollection = new Backbone.Collection([{}]);
var ChildView = Mn.View.extend({
    template: false,
    initialize: function(options){
        console.log(options.foo); // => "bar"
        console.log(options.childIndex); // => "0"
    }
});
var CollectionView = Mn.CollectionView.extend({
    collection: myCollection,
    childView: ChildView,
    childViewOptions: function(model,index){
        // do some calculations based on the model
        return {
            foo: 'bar',
            childIndex: index
        }
    }
});
var collectionView= new CollectionView();
collectionView.render();

4. CollectionView’s isEmpty

引用官网描述

If you want to control when the empty view is rendered, you can override isEmpty:

var myCollection= new Backbone.Collection([{}]);
var ChildView = Mn.View.extend({
    template: false
});
var MyEmptyView = Mn.View.extend({
    template: _.template('Nothing to display'),
    initialize: function(options){
        console.log(options.foo); // => "bar"
    }
});
var MyCollectionView= Mn.CollectionView.extend({
    collection: myCollection,
    childView: ChildView,
    emptyView: MyEmptyView,
    isEmpty: function(options){
        //this.collection.add({aaa: 'aaa'}); //若增加,则不为empty
        return this.collection.length < 2
    },
    emptyViewOptions:{
        foo: 'bar'
    }
});
var myCollectionView = new MyCollectionView();
myCollectionView.render();
$('body').append(myCollectionView.$el);

5. CollectionView’s render

引用官网描述

The render method of the collection view is responsible for rendering the entire collection. It loops through each of the children in the collection and renders them individually as a childView.

//此处定义的长度为2,运行结果会有两个Some text
var myCollection =new Backbone.Collection([{},{}]);
var MyView= Mn.View.extend({
   template: _.template('Some text')
});
var MyCollectionView = Mn.CollectionView.extend({
    collection: myCollection,
    childView: myView
});
var myCollectionView = new MyCollectionView();
myCollectionView.render();
$('body').append(myCollectionView.$el);

6. Automatic Rendering

Collection发生改变的时候,CollectionView会自动render

var myCollection = new Backbone.Collection([{}]);
var MyView = Mn.View.extend({
    template: _.template('Some text')
});
var MyCollectionView = Mn.CollectionView.extend({
    collection: myCollection,
    childView: MyView,
    onRender:function(){
        this.collection.each(function(model){
            console.log('Collection has been rendered,foo:'+model.get('foo'));
        })

    }
});
var myCollectionView = new MyCollectionView();
myCollection.reset([{foo:'foo'}]);
myCollectionView.render();
$('body').append(myCollectionView.$el);
myCollection.reset([{foo:'bar'}]);
//-result-
//Collection has been rendered,foo:foo
//Collection has been rendered,foo:bar

7. CollectionView’s destroy

引用官网描述

CollectionView implements a destroy method which automatically destroys its children and cleans up listeners.

var myCollection = new Backbone.Collection([{}]);
var MyView = Mn.View.extend({
    template: _.template('Some text')
});
var MyCollectionView = Mn.CollectionView.extend({
    collection: myCollection,
    childView: MyView,
    onDestroy: function(){
        console.log('CollectionView has been destroyed');
    }
});
var myCollectionView = new MyCollectionView();
myCollectionView.render();
$('body').append(myCollectionView.$el);
myCollectionView.destroy();

8. Child Event Bubbling *

The collection view is able to monitor and act on events on any children they own using childViewEvents and childViewTriggers. Additionally when a child view triggers an event, that event will bubble up one level to the parent collection view.

var myModel= new Backbone.Model()
var myCollection = new Backbone.Collection([
    {title: 'Item 1', order:1 },
    {title: 'Item 4', order:4 },
    {title: 'Item 3', order:3 },
    {title: 'Item 2', order:2 }
]);
var SomeChildView = Mn.View.extend({
    model: myModel,
    tagName: 'li',
    //动态内容写法<%= title %>
    template: _.template('<a>Title: <%= title %></a>'),
    //子View事件
    triggers:{
        'click a': 'select:item'
    }
});
var MyCollectionView = Mn.CollectionView.extend({
    childView: SomeChildView,
    collection: myCollection,
    tagName: 'ul',
    //要以onChildview为前缀
    onChildviewSelectItem:function(childView){
        console.log('item selected:' + childView.model.cid);
    }
});
var myCollectionView= new MyCollectionView();
myCollectionView.render()
$('body').append(myCollectionView.$el);

注意:一定要以onChildview为前缀

9. Rendering Tables

Tables Using Marionette 3

<!--DOM-->
<div id="region"></div>

<!--Template-->
<script id="table" type="x-template/underscore">
    <thead>
        <tr>
            <th>ID</th>
            <th>Body</th>
        </tr>
    </thead>
    <tbody></tbody>
</script>
<script id="row-template" type="x-template/underscore">
    <td><%- id %></td>
    <td><%- text %></td>
</script>
//使用了行模板的View
var RowView=Mn.View.extend({
    tagName:'tr',
    template: '#row-template'
});
//行的集合,所以为CollectionView,在DOM中行的集合放在tbody中
var TableBody = Mn.CollectionView.extend({
    tagName: 'tbody',
    childView: RowView
});
//整个表格为一个View,使用了表格模板
var TableView = Mn.View.extend({
    tagName: 'table',
    className: 'table table-hover',
    template: '#table',
    regions: {
        body:{
            el: 'tbody',
            replaceElement: true
        }
    },
    onRender: function(){
        this.showChildView('body',new TableBody({
            collection: this.collection
        }))
    }
});
//表格数据集
var list =new Backbone.Collection([
    {id:1,text: 'text 1'},
    {id:2,text: 'text 2'}
]);
//实例化一个table
var myTable = new TableView({
    collection: list
});
//渲染
var myApp = new Marionette.Application({
    region: '#region'
});
myApp.showView(myTable);

10. Rendering Trees

//--Data--
var tree = new Backbone.Collection([
    {
        nodeName: 'Parent 1',
        nodes:[]
    },
    {
        nodeName: 'Parent 2',
        nodes:[
            {nodeName:'Child 1',nodes:[]},
            {nodeName:'Child 2',nodes:[]}
        ]
    },
    {
        nodeName: 'Parent 3',
        nodes:[
            {nodeName:'Child 1',nodes:[]},
            {nodeName:'Child 2',nodes:[
                {nodeName:'Child 1',nodes:[]},
                {nodeName:'Child 2',nodes:[]}
            ]}
        ]
    }
]);
//--View--
var TreeNode = Mn.View.extend({
    tagName:'li',
    template: '#node-template',
    regions:{
        tree:{
            el: 'ul',
            replaceElement: true
        }
    },
    onRender:function(){
        var nodes=this.model.get('nodes');
        if(nodes.length){
            var treeView = new TreeView({
                collection: new Backbone.Collection(nodes)
            });
            this.showChildView('tree',treeView);
        }
    }
});
//--Collection View--
var TreeView = Mn.CollectionView.extend({
    tagName: 'ul',
    childView: TreeNode
});
//--实例化并渲染到页面--
var treeView= new TreeView({
    collection: tree
});
treeView.render();
$('body').append(treeView.$el);
 类似资料: