KnockoutJS double binding widget application

2019-08-03 05:40发布

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.

1条回答
够拽才男人
2楼-- · 2019-08-03 06:30

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.

查看更多
登录 后发表回答