mustache.js渲染带事件的模板

http://zccst.iteye.com/blog/2183111

最近遇到这样一个问题,预览内容可点击,问题是通过$.Mustache.render("templateId",data)渲染后的返回结果是一个字符串。 

实现方案有两个:一个是在Backbone的events中绑定事件,一个是对返回后的String使用jQuery的$(html).find("#target").click(); 

方案一:在Backbone的events中绑定事件 

var PreviewView = Backbone.View.extend({
        events: {
            'click .new_bt a' : 'demoClick',
        },
        initialize: function(options){
            this.model.bind('change:list', this.renderPreviewView, this);

            this.renderPreviewView();
        },
        renderPreviewView: function(){
            this.$el.empty();

            var data = this.model.toJSON();
            
            //方法1:使用$.Mustache.render();
            var html = $.Mustache.render('crownCommonKeyPreview-Pc', this.formatData(data.list));
            this.$el.html(html);

            //方法2:使用$("#xx").mustache("",data);
            //this.$el.empty().mustache('crownCommonKeyPreview-Pc', this.formatData(data.list));

            //方法3:使用原生的Mustache
        },
...
})

原理:Backbone使用的是事件代理,把html填充到el中后,el自然代理html中元素绑定的事件。 

方案二:对返回后的String使用jQuery的$(html).find("#target").click(); 

var PreviewView = Backbone.View.extend({
        events: {
        },
        initialize: function(options){
            this.model.bind('change:list', this.renderPreviewView, this);

            this.renderPreviewView();
        },
        renderPreviewView: function(){
            this.$el.empty();

            var data = this.model.toJSON();
            
            //方法1:使用$.Mustache.render();
            var html = $.Mustache.render('crownCommonKeyPreview-Pc', this.formatData(data.list));
            this.$el.html(html);
            this.$el.find(".new_bt a").click(function(){alert("aaa")});
            
            //方法2:使用$("#xx").mustache("",data);
            //this.$el.empty().mustache('crownCommonKeyPreview-Pc', this.formatData(data.list));

            //方法3:使用原生的Mustache
        },
...
})
原文地址:https://www.cnblogs.com/goldenstones/p/4685665.html