Magento – Magento 2 : knockout data-bind:click not working

knockoutmagento2

I added phtml file using ajax response. There are two buttons available in that phtml file.

Buttons.phtml :

<div id="rh-buttons-temp" class="actions" data-bind="scope:'rh-buttons'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <button type="submit" title="Select" class="action primary" id="rh-select-btn" data-bind="click:addCustomOptions()">
        <span>Select</span>
    </button>
    <button type="button" title="Cancel" class="action" id="rh-cancel-btn" data-bind="click:addCustomOptions()">
        <span>Cancel</span>
    </button>
    <script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "rh-buttons": {
                        "component": "RH_Custom/js/knock"
                        }
                    }
                }
            }
    }
    </script>
</div>

MainFile.phtml :

<div id="rh-ko-example" data-bind="scope:'rh-ko-scope'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "rh-ko-scope": {
                        "component": "RH_Custom/js/kotemplate",
                        "template" : "RH_Custom/kotemplate"
                        }
                    }
                }
            }
    }
    </script>
    <div style="display:none" class="product details product-item-details">
        <div class='custom'>
        </div>
    </div>
</div>

This Buttons.phtml file added in <div class='custom'></div> using ajax response.

Now, when click on Select Button then addCustomOptions() function call should be call. But, it's not working.


EDIT :

knock.js

define(
[
    'jquery',
    'uiComponent',
    'ko',
    'RH_Custom/js/kotemplate'
],
function($,Component,ko,kotemplate) {
    'use strict';
     return Component.extend({
        initialize: function () {
            alert("knock call");
            self = this;
            this._super();
            // kotemplate.addCustomOptions(); 
        },
        addCustomOptions : function()
        {
            console.log('knock custom options');
        }
    });
});

alert call successfully on above file. But, kotemplate.addCustomOptions() is not working. It returns error :

Uncaught TypeError: kotemplate.addCustomOptions is not a function

Where I do mistake?

Please help me.

Thanks.

Best Answer

You can't directly call the knockout method. Instead, add $parentwhile calling it. something like below.

 <button type="button" title="Cancel" class="action" id="rh-cancel-btn" data-bind="click:$parent.addCustomOptions()">
    <span>Cancel</span>
</button>