user210757
user210757

Reputation: 7386

knockout(js) to the (html)head

Does knockout not work in the head of an HTML doc?

I am trying to bind the href of stylesheet -

<html>
<head>

<link type="text/css" data-bind="attr: { href: myStyleSheet }" rel="stylesheet">

</head>
<body>

<script>
var ViewModel = function() {
    this.myStyleSheet = ko.observable('/css/stylea.css');
};
ko.applyBindings(new ViewModel());
</script>

</body>
</html>

The dynamic dom just looks like this -

<link rel="stylesheet" type="text/css" data-bind="attr: { href: myStyleSheet }">

Nothing happens.

Upvotes: 2

Views: 246

Answers (1)

Ian
Ian

Reputation: 34489

You can specify a target as the 2nd parameter of ko.applyBindings(). I'm not sure if you can specify the head, give it a try. If you don't specify anything it kicks into the following code:

ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
    // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
    if (!jQueryInstance && window['jQuery']) {
        jQueryInstance = window['jQuery'];
    }

    if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
        throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
    rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional

    applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};

Here you can see it picks the window.document.body as the default so that won't get the head.

Upvotes: 3

Related Questions