动态视图模型的淘汰赛
互联网上有大量关于如何使用 Knockout 处理动态视图(通过 ajax 调用)的信息,但是动态视图模型有最佳实践吗?
例如,假设我有一个单页应用程序,它根据角色、用户选择、上下文等(通过 ajax)呈现不同类型的表单(具有不同的输入字段)。我不仅会为每个表单使用模板,而且我'我想对视图模型做同样的事情,因为每个视图模型可能有许多非常不同的属性,并且为每个可能的模板使用一个庞大的视图模型是不切实际的。
我对 ko 有点菜鸟,它可能不适合以这种方式使用。非常感谢任何建议。
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?
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此类操作的一种流行方法是拥有一个托管子视图模型的主视图模型。
这是定义具有模板和关联数据的“模型”对象的一个非常基本的示例。
然后,您可以像这样使用它:
http://jsfiddle.net/rniemeyer/29kWf/
显然,您不太可能在选择中绑定模型的选择,但它有助于展示它是如何工作的。您的模型可以是属性名称与键匹配的对象,而不是数组。
“模型”对象中的“数据”将是您的子视图模型。
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.
Then, you could use it like:
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.
我面临着同样的问题。
尝试 Knockout 命名空间
I'm Facing the same problem.
Try Knockout Namespaces