Search code examples
javascriptknockout.jsknockout-3.0knockout-binding-handlers

Passing an unknown function in a knockout binding (foreach) - is it possible?


For a simple example, lets say this is my repeater:

<ul data-bind="foreach: items">
    <li data-bind="text: property1, attr: { onclick: some_unknown_function }"></li>
</ul>

I want whoever is using this code to be able to pass in a function of their choosing, NOT in the model itself that will run onclick - is that possible? Would there be a way to assign it to the model and set it as the click binding? I can't seem to figure this out...


Solution

  • Figured out a pretty easy way, sometimes I forget how literal JS is...

    Changed my repeater to this:

    <ul data-bind="foreach: items">
        <li data-bind="text: property1, click: myClick }"></li>
    </ul>
    

    And my model to this:

    function Item(options) {
        var self = this;
        options = options || {};
    
        self.property1 = ko.observable(options.property1 || '');
        self.onclick = options.onclick || null;
    
        self.myClick = function () {
            if (self.onclick != null) {
                self.onclick()
            }
        }
    }