【问题标题】:underscore template - jQuery object reference下划线模板 - jQuery 对象引用
【发布时间】:2016-01-09 03:48:30
【问题描述】:

我需要在模板的某处渲染图表:

{{= new App.components.Doughnut() }}

Doughnut 构造函数返回一个已编译模板的字符串,但在Doughnut 的逻辑中,我有一个超时,它改变了图表值。问题是,我无法在内部保存实例,以便以后访问它,因为它被转换为字符串并作为编译模板的一部分打印,所以实例丢失了。

我有无数地方写过它:

{{= new App.components.Doughnut({radius:50,50}).render() }}

有没有办法以某种方式从工厂内部保存对实例的引用,以便稍后我可以访问它?

我想可能会以某种方式在模板中放置占位符(具有自己的设置),因此只有在编译后,实例才会附加到每个占位符。

App.components.Doughnut = function(settings = {}){
    var template = _.template(templates["components\\plotting\\doughnut"]);
    this.settings = $.extend({}, { radius:[70,70]}, settings);
    this.compiledTemplate = template(this.settings);
    this.doughnut = $(this.compiledTemplate);
};

App.components.Doughnut.prototype = {
    render : function(){
        // animate the value with delay
        setTimeout( this.setValue.bind(this), 1000 );
        return this.compiledTemplate;
    },

    setValue: function (value = this.settings.value){
        // do something 
        this.doughnut.doSomething()
    }
};

【问题讨论】:

    标签: jquery underscore.js template-engine


    【解决方案1】:

    最后在我的模板中写了这个:

    <script type='js/template-doughnut'>
       {"value" : 80}
    </script>
    

    然后在模板控制器中,我写:

    $target.find('script[type="js/template-doughnut"]').each(function(){
        try{
            var data = JSON.parse(this.innerHTML),
                doughnut = new App.components.Doughnut( data );
            // This way reference to the element is saved
            $(this).replaceWith(doughnut.elm); 
        }
        catch(err){}
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多