Backbone之旅——Collection and View篇

上篇文章說了Model,此次說說Collection,collection就是model的集合,用來裝載model對象的服務器

定義方法fetch

var Persons = new Backbone.Collection.extend({this

        model: person,url

        initialize:function(){}spa

});server

上面就定義了一個簡單的collection,關聯的Model就是上篇文章定義的Person對象

collection通常是用來去集合數據的,因此會配置View一塊使用,下面來定義一個Viewget

 

var PersonView = new Backbone.View.extend({it

  el: $("body"), //el能夠同過set方法設置io

     initialize: function(){

            this.persons = new Persons();     

            this.render();      

     },

     render: function(){

           var self = this;

           self.persons.fetch({

                 url:"/getPersons",

                 success: function(collection, res, options){

                        //獲取成功後裝載數據模板,並輸出到頁面便可

                },

                 error: function(collection, res, options){}

           });

    }

});

一個View定義完成,配合Collection從服務器獲取數據集合,主要是render方法中的fetch的使用,此方法是Backbone.sync的一個get請求方法經過回調獲取server的數據,最後加載到page當中的模板中便可,基本邏輯就這樣了,這是本人理解

相關文章
相關標籤/搜索