淘汰赛与动态的ViewModels [英] knockout with dynamic viewmodels

查看:164
本文介绍了淘汰赛与动态的ViewModels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有大量的关于如何(通过AJAX调用)处理动态的观点与淘汰赛的interwebs信息,但有动态的ViewModels最佳做法?

There's a ton of info on the interwebs about how to handle dynamic views (via ajax calls) with Knockout, but is there a best practice for dynamic viewmodels?

例如,假设我有一个单页的应用程序,使得(通过AJAX)不同类型的表单(具有不同的输入字段),基于角色,用户的选择,环境等,不仅我会用模板为每个表单,但我想对视图模型做同样的,因为每个视图模型可能有许多非常不同的特性,这将是不切实际的有一个庞大的视图模型为每一个可能的模板。

For instance, say I have a single page app that renders (via ajax) different types of forms (with different input fields) based on role, user choices, contexts, etc. Not only would I use templates for each form, but I'd like to do the same for the viewmodel, since each viewmodel may have many very different properties and it wouldn't be practical to have one massive viewmodel for every possible template.

我有点用劫一枝新秀,它可能不会意味着以这种方式使用。任何意见是多少AP preciated。

I'm a bit of a rookie with ko, and it may not be meant to be used in this fashion. Any advice is much appreciated.

推荐答案

一个流行的方式做这种类型的事情是有承载子视图模型的主视图模型。

A popular way to do this type of thing is to have a main view model that hosts sub-view models.

下面是定义一个有一个模板和相关的数据模型对象的真正的基本的例子。

Here is a really basic example of defining "model" objects that have a template and associated data.

function Model(key, template, data) {
   this.key = key;
   this.template = ko.observable(template);
   this.data = data; 
}

var viewModel = {
   models: ko.observableArray([
       new Model("user", "userTmpl", { first: "Bob", last: "Smith" }),
       new Model("item", "itemTmpl", { name: "MyItem", description: "Here are some details" })
   ]),
   selectedModel: ko.observable()
};

ko.applyBindings(viewModel);

然后,你可以用它喜欢的:

Then, you could use it like:

<select data-bind="options: models, optionsText: 'key', optionsCaption: 'select a model...', value: selectedModel"></select>

<hr />

<div data-bind="with: selectedModel">
    <div data-bind="template: { name: template(), data: data }"></div>    
</div>


<script id="userTmpl" type="text/html">
    <span data-bind="text: last"></span>, <span data-bind="text: first"></span>
</script>

<script id="itemTmpl" type="text/html">
    <h3 data-bind="text: name"></h3>
    <div data-bind="text: description"></div>
</script>

http://jsfiddle.net/rniemeyer/29kWf/

显然,你不可能绑定模式的选择中选择,但它有助于展示它是如何工作的。而不是一个数组你的模型可能是一个对象的属性名相匹配的关键。

Obviously, you wouldn't likely bind the selection of the model in a select, but it helps show how it can work. Rather than an array your models could be an object with the property names matching the key.

在模式对象的数据将是您的子视图模型。

The "data" in the "model" objects would be your sub-view models.

这篇关于淘汰赛与动态的ViewModels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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