Best Practice to applyBindings with Single Page Applications (SPA)

100 views
Skip to first unread message

Wet Feet

unread,
Aug 31, 2017, 12:03:47 AM8/31/17
to KnockoutJS
I have been using Knockout with a few SPA.

In SPA, multiple views and pages may exist within the same <body> element as <div>. A typical example is a JQuery mobile app. <div> element, nodes may also get added or removed dynamically over time by JavaScript as the user interacts with the app, which means they need to re-applyBindings() as they get created and destroyed. I suppose the JavaScript UI framework/library is doing DOM manipulation underneath using document.createElement(.).

Now, by default Knockout apply bindings to the whole page on start. If there are views/pages dynamically generated or loaded during run-time later on, by default, calling applyBindings will trigger "You cannot apply bindings multiple times to the same element."

Currently, what I am doing is applying bindings selectively to individual page <div> using:

ko.applyBindings( pageViewModel, document.querySelector('#pageDivElement') )


While my current style works, I wonder if I am doing things right, and if there are other better ways that Knockout is designed to deal with SPA. 
Reply all
Reply to author
Forward
0 new messages