Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS - Multiple partial views within on main view?

I am trying to port an existing asp mvc app over to use knockoutjs (pure js/html) as I no longer really need any of the functionality within asp mvc. However one problem I can forsee is the way I am handling some of my pages.

I have one page which contains about 12 partial views, each partial has its own model. Now with Knockout JS it seems like you should only really have 1 viewmodel/view per page, however the page I have contains a large amount of information, the sections would be akin to:

  • Customer Details
  • Customer Address
  • Customer Recent Orders
  • Customer Cards
  • Customer Funds
  • ...

To make things more tricky if some details change in on part, it needs to change data in another part. So lets say you remove a card it then needs to tell the funds control that it no longer has a card so wont have funds. (This is all an abstract example, but hopefully illustrates the point)

So I am a bit unsure how to do this in knockout, as that would rather have it as one big model, which I would be happy with doing but it contains ALOT of information. As well as multiple forms, as you can update your address without having to update everything else.

So should I just make one large model for this view and just deal with it? or is there a way to have views talk to each other?

like image 581
somemvcperson Avatar asked Jun 28 '11 16:06

somemvcperson


2 Answers

I would caution against one monster view model because it creates a tight coupling that you'll want to avoid in complex applications.

A better solution is to build a pub/sub system on top of ko.subscribable. Communication between view models is then facilitated by managing subscriptions to various events. It's a little more work upfront, but it will pay dividends down the road.

Here is a blog post that expands on the topic. I highly recommend this blog. Its a great resource for knockout-specific challenges and strategies.

like image 73
elDuderino Avatar answered Oct 31 '22 02:10

elDuderino


My strategy is to use a one large view model. No matter you put it, the partial views are a server-side concept and once everything transfers to the client side, it would be large amount of data information in a single page.

However to make things manageable I ensure that every Javascript manipulation code is written in it's own Partial view. This makes it easier to track functionality and it's respective code.

So basically you populate your main Customers array object in the main page and then call functions to populate Details, Addresses etc. which are respectively defined in each of the partial view.

like image 32
neebz Avatar answered Oct 31 '22 04:10

neebz