如何正确构造KnockoutJS应用程序 [英] How to properly structure a KnockoutJS application

查看:78
本文介绍了如何正确构造KnockoutJS应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何正确构建KnockoutJS应用程序.

I am wondering how to structure a KnockoutJS application the right way.

  • 官方文档几乎总是只使用一个ViewModel

仅执行了几个函数后,我的代码就变得非常混乱,并且来自面向对象的背景,我对这样的体系结构非常敏感.因此,必须有一个更好的解决方案.

After only a few implemented functions my code became very confusing and coming from an object-oriented background I am very allergic to architecture like that. So there must be a better solution.

由于对JavaScript不太熟悉,我正在搜索Stackoverflow并发现那些三个选项.所以我尝试了前两个选项,但我对它们不满意:

Being not very experienced with JavaScript I was searching Stackoverflow and found those three options. So I tried the first two options and I am not happy with them:

  • 具有多个ViewModel ,例如
  • Having multiple ViewModels like here.

我发现很难决定哪个DOM元素获取什么ViewModel.另外,还有一些从DOM元素外部调用的函数.也许我在这种架构上使用的ViewModels太少了,但是ViewModels之间的通信似乎有所不同,我希望这在某种程度上是不必要的.那么如何正确地做到这一点呢?

I find it very difficult to decide what DOM-element gets what ViewModel. Also there were several functions called from outside the DOM-element. Maybe I used too little ViewModels with this kind of architecture but communicating between ViewModels seemed to be different and somehow shouldn't be necessary I hope. So how to do that properly?

  • Having sub views and utilizing the with binding (the second option from those three).

这是我首选的体系结构类型,因为您可以在一个视图模型中进行文档范围的绑定,但是您也可以将代码结构化为子块,并通过使用with绑定将它们绑定到所需的任何位置.不过,此选项需要对象文字而不是函数,如

This was my preferred type of architecture because you can have document-wide bindings out of one view model but you can also structure your code into sub-chunks and bind them to wherever you want by using the with binding. This option though requires object literals instead of functions, which are inferior as described in this answer.

我还没有尝试过方法三,因为它似乎有点过大了,而且还使用了对象常量.

I haven't tried method three because it seems a little overkill and also uses object literals.

那么有没有一种方法可以构造我的代码,并且还可以完全控制而不使用对象文字?

我希望这不要太令人困惑:-P

I hope this was not too confusing :-P

推荐答案

对于您提到的任何选项,您都不需要使用对象文字.这些示例只是使用它们来简化代码.您可以选择以自己认为合适的任何方式来创建单个视图模型.

For any of the options that you mentioned, you do not need to use object literals. The samples just used them to simplify the code. You can choose to create the individual view models in any way that you see fit.

例如,在#3中,您可以使用类似以下的构造函数: http://jsfiddle.net /rniemeyer/PctJz/149/.当然,实际数据将传递给函数,而不是静态的.与#2相同,只需将其包装在视图"对象中即可.

For example in #3, you can use a constructor function like: http://jsfiddle.net/rniemeyer/PctJz/149/. Of course, the actual data would get passed into the function rather than being static. Same with #2, you just would have it wrapped in the "View" object.

这篇关于如何正确构造KnockoutJS应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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