Question

Imagine n buttons on the page, each opening up a div on-click. There is in fact a single div, which gets re-associated to each button on click. I want the data on the div to be binded to the ViewModel instances for each button.

I don't know if I'm on the right path but so far I have an instance of the VM object connected to each button. When button x is clicked I can get its corresponding VM and re-applyBinding to the div. In this case I need to decouple the old binding -which I'm not sure how to do.

My approach seems fine to me, but that could be because I come from a C#/Java background and treat everything as objects and references. Maybe there is a better way?

Was it helpful?

Solution

In a typical KO application, you would want to aim towards applying bindings a single time. Knockout's templating and control-flow bindings can help you to "swap" content in and out.

For example, you may have a collection of things like:

this.vms = [
   { id: 1, data: {} },
   { id: 2, data: {} },
   { id: 3, data: {} }
];

Then, you could have an observable to represent the currently selected item:

this.currentVM = ko.observable();

Now, you can generate your buttons, by doing a foreach over the vms. When, you click on one of the items, then you can populate currentVM with that item.

You can then render a section against the currentVM like:

<div data-bind="with: currentVM">
    ...some content
</div>

Knockout will handle currentVM being empty (nothing rendered) and then will handle swapping the content in and out for you. Brief sample here: http://jsfiddle.net/rniemeyer/tk3nJ/

The answer to this question, goes a bit further with this idea: Example of knockoutjs pattern for multi-view applications

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top