How to properly structure a KnockoutJS application

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

  • The official documentation almost always uses just one single 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.

    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:

  • Having multiple ViewModels like here.
  • 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).
  • 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.

    So is there a method to structure my code and also have full control without using object literals?

    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.

    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.

    链接地址: http://www.djcxy.com/p/11312.html

    上一篇: 如何在ios开发中从mp3文件中提取元数据

    下一篇: 如何正确构建KnockoutJS应用程序