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();

 

posted @ 2016-06-13 16:46  Jiemoo  阅读(338)  评论(0编辑  收藏  举报