Search code examples
knockout.jsknockout-3.0knockout-3.2

When to create new view models in Knockout.js


I've seen there's generally a bit of confusion when talking about multiple view models in knockout.js

The ko documentation doesn't really explain very much how to deal with multiple view models, how to communicate between them or when should they be considered.

I found this site explaining different ways of creating multiple view models and how to interact with them.

I gave it a try and I created a master model with different submodels:

var MasterModel = function(){
    this.orders = new ordersViewModel(),
    this.dates = new datesViewModel(),
    this.equipment = new equipmentViewModel();
};

After that, I found myself having to use with: nameOfModel in many places (and create extra wrappers or HTML comments for it) or even just using the view model's name as a prefix data-bind="foreach: orders.getList()".

Besides that, then we have the problem of communicating between them, and although it can be solved somehow, it doesn't seem as simple as when dealing with a single view model.

My question is, is it worthy to create multiple view models? If so, when? It seems it only adds more difficulties and I do not end up seeing the advantages of it. (yeah, they say its maintains modularity... but I don't end up seeing a clear advantage )


Solution

  • I agree with Anish Patel that it depends and it is about separation of concerns and keeping your classes in the Single Responsibility Principle (only do one thing with each class, which I've found difficult to do with view models). You may also need to think about making your view models testable with Jasmine or another JS test framework.

    Using with: in the HTML is not a bad approach in my opinion.

    RequireJs can help with making things modular and getting dependencies working.

    ko.postbox allows you to do publish/subscribe communications between the view models without having to couple them together. This was in the link you mentioned. You can also communicate by having callback functions passed int your view models.

    Durandal is a good suggestion. I'm also interested in Aurelia by Rob Eisenberg who is the creator of Durandal, but it is still in beta as of 7/2/2015. That will load modules with a standardized SystemJs and should make modularizing view models easier to do.