Knockoutjs使用多个视图模型 [英] Knockoutjs working with multiple view models

查看:104
本文介绍了Knockoutjs使用多个视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让Knockout js与jQueryMobile一起使用,并且在页面之间移动时遇到一些问题.

I am trying to get Knockout js working with jQueryMobile and am hitting a few problems when moving between pages.

我想尝试在JQM中保持页面转换,因此我想使用多页面选项(在一个html文件中定义了多个页面)或将其他页面加载到DOM中,如默认AJAX行为中所述文档部分.

I would like to try and keep the page transitions in JQM and therefore I would like to use either the multiple page option (multiple pages defined in one html file) or load the additional pages into the DOM as detailed in default AJAX behaviour section of the documentation.

JQM页面过渡文档

我有两个单独的Knockoutjs页面,每个页面都有一个单独的视图模型.在我尝试通过JQM将它们链接在一起之前,这两个页面都可以正常工作.

I have two individual Knockoutjs pages working both with a separate view model on each. Both pages work perfectly until I attempt to link them together through JQM.

我尝试加载哪个页面,但在另一页面上遇到与映射有关的错误.我只能假定两个页面都已加载到单个DOM中,并且当Knockout应用绑定时,它正在查找不存在的属性.

Whichever page I attempt to load I get an error relating to a mapping on the other page. I can only assume that both pages are loaded into the single DOM and when Knockout applies the bindings it is looking for properties that do not exist.

我试图制作一个jsFiddle来演示这一点.

I have attempted to make a jsFiddle to demonstrate this.

JQM-淘汰赛小提琴

我对JQM和Knockout都是陌生的,因此对您的帮助表示感谢.如果我采用完全错误的方法,那么我将不胜感激有人将我指向正确的方向.

I am new to both JQM and Knockout so any help appreciated. If I am taking completely the wrong approach then I would appreciate someone pointing me in the right direction.

我会更好地尝试在整个网站上使用一个ViewModel吗?如果没有,如何在JQM中使用Knockoutjs?

Would I be better attempting to use one ViewModel for the whole site? If not how can I use Knockoutjs with JQM?

推荐答案

可以接受整个网站的一个主"视图模型.然后,您可以执行以下操作:

One "master" view model for the whole site would be acceptable. Then, you could do something like this:

var masterViewModel = {
   viewModelOne: ...,
   viewModelTwo: ...
}

或者,您可以调用.applyBindings重载以将绑定应用于单个元素,而不是整个DOM:

Alternately, you can call the .applyBindings overload to apply bindings to individual elements, rather than the whole DOM:

ko.applyBindings(new modelOne("Test", "One"), $("#one")[0]);
ko.applyBindings(new modelTwo("Test", "Two"), $("#two")[0]);

我个人建议第二种方法.

Personally, I'd recommend the second approach.

这篇关于Knockoutjs使用多个视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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