knockout.jsknockout-binding-handlers

How can a Knockout binding be applied to the <html> element?


I would like to dynamically set the font-size on the root element using a custom Knockout bindinghandler which does a calculation based on the width of the browser window.

When I tried to apply the binding, nothing seemed to happen, so I tried to apply a simple css binding:

<html data-bind="css: { bindinghandlertest: true }">

But the binding handler didn't seem to add the class.

Question: Can KO bindings only be applied to <body> and its children?

Note: I am initializing all bindings on the whole page by simply calling ko.applyBindings(); once on DOM ready, with no parameters at all.


Solution

  • You can apply bindings to a specific html element as explained here

    Specifically:

    Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.applyBindings(myViewModel, document.getElementById('someElementId'))

    In you case, you can them call

    ko.applyBindings(myVM, document.documentElement);
    

    by default, the DOM node is the body, as you can see from the source:

    rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional