外部模板和" EL"与淘汰赛和RequireJS? [英] External templates and "el" with Knockout and RequireJS?

查看:312
本文介绍了外部模板和" EL"与淘汰赛和RequireJS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用淘汰赛的ViewModels为可放置到页面上的任何(或多个)DOM节点自足部件。我曾在骨干的做法,似乎运作良好,我想这个概念转换为淘汰赛。

I am trying to use Knockout ViewModels as self-contained "widgets" that can be placed into any (or multiple) DOM nodes on the page. I had an approach in Backbone that seemed to work well and I'm trying to convert the concept to Knockout.

在骨干视图,我会做这样的事情,使用RequireJS文本插件拉模板,并将其注入到EL:

In Backbone view I would do something like this, using the RequireJS text plugin to pull the template and inject it into the el:

define(['text!templates/myTemplate.html',], function(templateHTML){
    var view = Backbone.View.extend({

        initialize:function() {
            // yes I know the underscore templating stuff doesn't apply in Knockout
            this.template = _.template( templateHTML );
            this.render();
        },

        render:function( ) {
            // the $el is provided by external code. See next snippet
            this.$el.append(this.template(myData));
            return this;
        }

        // other view behavior here

    });

    return view;
});

然后其他一些外部件code的可能这一观点放到现有的DOM节点:

And then some other piece of external code could place that view into an existing DOM node:

new MyBackboneView({el: $('#myExistingDivID')});

在淘汰赛中,我能找到这种方法最接近的是让在外部code 使用文本插件拉模板,它注入的div,然后应用KO绑定:

In Knockout, the closest I can find to this approach is to have the external code use the Text plugin to pull the template, inject it into the div, and then apply the KO bindings:

var mydiv = $('#myExistingDivID');
mydiv.html(myTemplateHTML);
ko.applyBindings(new MyKOViewModel(), mydiv[0]);

1 - 有没有在淘汰赛推荐的方式有视图模型本身注入基于骨干的厄尔尼诺的概念相当于外部HTML模板?最关键的是,外部(路由器-ISH)code控制的其中,内容将被放置,但视图模型控制内容和在哪里得到模板的实际细节。

1 - Is there a recommended way in Knockout to have the ViewModel itself inject the external template HTML based on the equivalent of Backbone's "el" concept? The key is that the external (router-ish) code controls where the content will be placed, but the ViewModel controls the actual details of the content and where to get the template.

2 - ?如果是,的我采取这种方法,还是我滥用这一淘汰赛和MVVM旨在使用方式

2 - If yes, should I take this approach, or am I abusing the way that Knockout and MVVM are intended to be used?

推荐答案

您可以覆盖默认的模板源,然后使用具有默认渲染引擎像

You can override the default template source and then use that with the default render engine like

var stringTemplateEngine = new ko.nativeTemplateEngine();
stringTemplateEngine.makeTemplateSource = function (template) {
    return new StringTemplateSource(template);
};
ko.setTemplateEngine(stringTemplateEngine);

简单的例子我做了

Quick example I did

http://jsfiddle.net/3CQGT/

这篇关于外部模板和" EL"与淘汰赛和RequireJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆