Magento 2 – How to Bind Knockout Event on Ajax HTML Response

javascriptknockoutjsmagento2

I have created custom functionality on item form on cart page like increment/decrement qty, remove product with a custom popup, custom move to wishlist by knockout js.

For knockout events, I created custom js and initialize it on form.phtml

<div data-bind="scope: 'remove-product'" id="cart-item-table">
    <form action="<?= /* @escapeNotVerified */ $block->getUrl('checkout/cart/updatePost') ?>"
              method="post"
              id="form-validate"
              data-mage-init='{"validation":{}}'
              class="form form-cart">

              ....
              ....
    </form>
</div>

<script type="text/x-magento-init">
    {
       "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "remove-product": {
                        "component": "Vendor_Module/js/removeproduct"
                    }
                }
            }
        }
    }
</script>

enter image description here

Now I have a third-party coupon code module which adds free gift product by applying the coupon code on cart page. For that, I just re-render item form layout on ajax response.

Everything is working fine except knockout events on item form. All knockout events stop working after re-render item form.

After some R&D, I found that we need to rebind knockout events after ajax response.

ko.applyBindings(removeproduct, $('#cart-item-table'));

It's showing error like parameter should ViewModel and element. I already defined it.

Any help would be appreciated…!

Best Answer

We need to re-bind js component by knockout applyBindings function on ajax response.

ko.applyBindings(new removeproduct(), $('#cart-item-table')[0]);

While removeproduct is viewModel Vendor_Module/js/removeproduct and cart-item-table is the element which I need to re-bind knockout events.