javascriptknockout.js

Knockout - Custom bindings - pass variable from init to update


First time using knockout.js for me.

I have the following binding:

ko.bindingHandlers.dateselect = {
    init: function (element) {

        var picker = new Pikaday({
            field: element,
        });

    },
    update: function (element) {

        var current = picker.getDate();

    }
};

In the init method, I initialise the datepicker and I'm trying to get the date in the update method, as shown above.

Problem being is I'm getting the following error:

picker is not defined

Is there any way to access the picker instance inside the update method?


Solution

  • You can do this by setting up helpers, which are stored to the element.

    E.g.

    function SomeBindingHelper(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var sharedVariable = "Banana";
    
        // Call on init.
        this.init = function () {
            console.log("init", sharedVariable);
        }
    
        // Call on update.
        this.update = function () {
            console.log("update", sharedVariable);
        }
    }
    
    ko.bindingHandlers.someBinding = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
           var bindingHelper = new SomeBindingHelper(element, valueAccessor, allBindings, viewModel, bindingContext);
           bindingHelper.init();
           ko.utils.domData.set(element, "someBindingHelper", bindingHelper);
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
           var bindingHelper = ko.utils.domData.get(element, "someBindingHelper");
           bindingHelper.update();
        }
    }