1

I have used Knockout JS app with in Magento 2.1.0, when I use:

ko.applyBindings(ViewModel, document.getElementById("custom")); 

It breaks the Knockout used by Magento and throws this error:

Uncaught Error: You cannot apply bindings multiple times to the same element.

Even i have tried with:

ko.cleanNode(document.getElementById("custom"));

Still the error exists

1 Answer 1

1

Magento automatically calls that method so if you integrate correctly with Magento 2's Knockout structure, it will be bound without you explicitly calling the method. Because the warning indicates that the binding has already occurred, it seems likely to me that Magento has already bond that element (although, it is difficult to tell for certain without more context in your question).

The file that calls ko.applyBindings() is Magento/Ui/view/base/web/js/lib/knockout/bootstrap.js. In that file, it calls the method without any parameters, such as the ViewModel. This is because Magento handles that view attributes like this: data-bind="scope: 'example.component'" Magento takes that and binds a scope (which would be a Javascript component, or requireJS alias to one) to the HTML.

If you are not already using it, I suggest that you take advantage of the X-Magento-Init script type to initialize your Knockout JS. You can read about it here: http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/js_init.html

The essence is that instead of document.getElementById("custom") you can do something more like:

#custom: {
     component: "MyComponent/js/jsfile"
}

Here is another article that you may find helpful as well: http://alanstorm.com/magento_2_knockoutjs_integration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.