2

我正在用 Knockout 替换 ASP.NET MVC+Knockout,我想删除 ASP.NET 并获得静态 js + html。

我的 ASP.NET 视图由 Partial 视图组成(我在我的项目中称它们为小部件),这个 Partial 视图很容易被 Knockout 组件替换。但我有一个问题:ASP.NET Partial 视图有一个布局(每个小部件都有一些 html 装饰),我怎样才能实现类似的淘汰赛组件视图?

简化示例。旧的 asp.net 方案:

查看.cshtml:

<div>
    @Html.Partial("SomeWidget")
</div>

SomeWidget.cshtml:

@{
    Layout = "~/Views/Shared/_WidgetLayout.cshtml"; <!-- parent layout for widget -->
}
<span>This is some widget</span>

_WidgetLayout.cshtml:

<div>
    <span>This is decorator for every widget</span>
    @RenderBody() <!-- render widget view here (SomeWidget.cshtml in this example) -->
</div>


新的仅淘汰赛计划:

查看.html:

<div>
    <some-widget></some-widget>
</div>


视图.js:

ko.components.register('some-widget', { require: 'app/SomeWidget' });

SomeWidget.html:

<span>This is some widget</span>


SomeWidget.js:

var view = require('text!/views/SomeWidget.html');
return { template: view };


如何在 Knockout 中替换 _WidgetLayout.cshtml?

4

1 回答 1

2

There are several ways you could possibly do this. The simplest way I can think of is to have a template component, and you nest the widget inside this. KO Components support nesting.

You can define a template component thus:

    ko.components.register("widget-template", {
        viewModel: function(params) {
            var self=this;
            self.WidgetName = params.widget;
        },
        template: "<div class='b'><span>This is decorator for every widget</i>
<div data-bind='component: { name: WidgetName }'></div></div>"
    });

To use this, you put the template-widget into your HTML, and pass the name of the widget as a parameter:

<widget-template params="widget: 'widget1'"></widget-template>

Then you define a widget as another component:

ko.components.register("widget1", {
    template: "<h3>Widget One</h3>"});

So now you have a re-usable template that can wrap any component. You can see more about this binding in the Knockout documentation.

See the full JS fiddle here: http://jsfiddle.net/Quango/a8h2bwtc/

Note that you can also make the name an observable rather than a static value, as seen here: http://jsfiddle.net/Quango/tnphvvgd/

于 2014-11-14T14:05:59.280 回答