backbone的view模板(updateView)

//加載並初始化模板對象
var templateHTML = loadTemplate("assets/templates/cis_culture.html");

var CultureView = Backbone.View.extend({//options...
    initialize : function(option) {
        //初始化VIEW並讓model與VIEW進行關聯
        this.model.view = this;
        //初始化VIEW的HTMLDOM對象
        this.render();
    },
    template : templateHTML, //VIEW對應的模板
    render : function() {
        var self = this;
        if (this.template) {
            //使用模板+數據拼裝DOM
            this.$el = $(this.template({
                data : this.model.attributes,
                encodeD : function(d) {
                    return encodeURIComponent(JSON.stringify(d));
                }
            }));
            
            appcan.button(this.$el,"btn-act",function(){
            })
        }
        //返回自身,便於promise調用
        return this;
    },
    updateView : function(model) { var self = this; var cltrTtl = model.get('cltrTtl'); var cltrType = model.get('cltrType'); $('.title', self.$el).html(cltrTtl); $('.type', self.$el).html(cltrType); }
});

//列表容器VIEW
var CultureListView = Backbone.View.extend({//options...

    initialize : function() {
        this.listenTo(this.collection, "add", this.add); this.listenTo(this.collection, "change", this.updateView); this.listenTo(this.collection, "remove", this.removeView); this.listenTo(this.collection, 'sort', this.sort);
    },
    collection : new CultureCollection(), //collection,用於存儲和管理數據
    el : '#list', //VIEW 對應 HTML 元素CSS選擇器
    pageNo : 1,
    $norecord : $("#norecord"),
    load : function(type) {this.collection.fetch({
            params : {
                data : data
            },
            success : function(cols, resp, options) {
            },
            error : function(cols, error, options) {
            }
        });
    },
    add : function(model) {
        var view = new CultureView({
            model : model
        });
        this.$el.append(view.$el);
    },
 updateView : function(model) { var view = model.view; if (view) { this.$el.prepend(view.$el); view.updateView(model); } },
    removeView:function(model){
        var view = model.view;
        view.remove();
    },
    sort : function() {
        for (var i = 0; i < this.collection.length; i++) {
            var model = this.collection.models[i];
            if (model.view) {
                this.$el.append(model.view.$el);
            }
        }
    }
});

var cultureListView = new CultureListView();
相關文章
相關標籤/搜索