Etheryte
Etheryte

Reputation: 25328

Remove data-bind attributes after binding

I'm using Knockout.js for a number of things in a project.
Among other things it's used to build XML config for a third-party tool on the fly, which requires a very specific, strict markup.

This means, that all resulting markup needs to be without any data-bind attributes.

Currently I can achieve this by additionally binding

<Element data-bind="attr: {'data-bind': false}" />

or alternatively doing a separate, additional loop over the whole resulting markup, removing all data-bind attributes.

Neither of the solutions are too straightforward, the first one meaning very verbose templating, the second requires an additional pass over the whole result.

Does Knockout offer a better alternative to remove all data-bind attributes after bindings have been applied?

Upvotes: 1

Views: 1790

Answers (1)

sroes
sroes

Reputation: 15053

Maybe preprocessNode can help:

You can hook into Knockout’s logic for traversing the DOM by providing a node preprocessor. This is a function that Knockout will call once for each DOM node that it walks over, both when the UI is first bound, and later when any new DOM subtrees are injected (e.g., via a foreach binding).

The following will remove the data-bind attribute:

ko.bindingProvider.instance.preprocessNode = function(node) {
    if (node.removeAttribute) {
        setTimeout(function() {
            node.removeAttribute('data-bind');
        }, 0);
    }
};

See http://jsfiddle.net/jfjbpbtq/

setTimeout is needed because knockout will read the data-bind attribute after calling preprocessNode.

Upvotes: 4

Related Questions