1

I have a scenario where I've developed a widget based application, which injects itself into the DOM of a consuming application. That widget uses KnockoutJS to render it's own UI, and it binds do it's own ViewModel.

The consuming application (possibly not mine) also uses KnockoutJS to render it's own UI with a totally different ViewModel.

What happens is that the consuming page loads and runs ko.applyBindings(hostPageViewModel). Then the widget loads and runs ko.applyBindings(widgetDataViewModel). Once the second applyBindings is executed, the consuming page looses the context of it's bound model and displays nothing. In debug, I can see the data render on the consuming application, then get wiped by the widget application.

Other than trying to maintain two totally different instances of Knockout (not even sure if this is possible but I was thinking about newing the widget version and calling it kotwo), is there a solution for this?

I can not applyBindings only one time because of the application within an application style of this design.

I'd love some help with this one if anyone has suggestions.

farina
  • 3,486
  • 6
  • 32
  • 44
  • I just found this [http://stackoverflow.com/questions/7342814/knockoutjs-ko-applybindings-to-partial-view] which I didn't know existed. It sounds like you can scope the bindings, but I am not sure this will do it. There doesn't appear to be documentation on this. I'd say the widget app could just applyBindings down from it's root, and be completely isolated from whatever consuming app, if this works. – farina Mar 15 '12 at 23:33
  • OK, never mind my question. The rootnode feature of KnockoutJS does EXACTLY what I need. Is there nothing that these guys haven't thought of? I need a job working with the Knockout team...amazing! – farina Mar 15 '12 at 23:47
  • Can you post how you solved your issue as an issue so that other users get directed correctly. – madcapnmckay Mar 16 '12 at 00:19
  • you basically wrote what I said, so you get the solution credit :). – farina Mar 16 '12 at 00:54

1 Answers1

3

I think you will need to scope your second apply bindings just to your widget containing div which is only added to the DOM after your widget loads and after your first applyBindings is called.

So the widget would call

ko.applyBindings(widgetViewModel, $widgetDiv);

This will stop them treading on each others toes.

As for having two versions of KO on the page, I'm not sure what the consequences are. Could you test for ko object and if not found include your files dynamically?

Hope this helps.

madcapnmckay
  • 15,782
  • 6
  • 61
  • 78
  • I was planning on using one version of KO...only instancing it if needed. The magic is in that extra rootnode param that I didn't know existed. – farina Mar 16 '12 at 00:55