Lodder
Lodder

Reputation: 19743

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?

Upvotes: 0

Views: 283

Answers (2)

sfcnzl
sfcnzl

Reputation: 33

may not have been the case at the time but for anyone stumbling across this in future, I've found the code below works.

ko.bindingHandlers.dateselect = {
    init: function (element) {
        this.sharedVar = true;
        var picker = new Pikaday({
            field: element,
        });
    },
    update: function (element) {
        console.log("sharedvar", this.sharedVar); 
        var current = picker.getDate();

    }
};

Upvotes: 2

Paul
Paul

Reputation: 2076

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();
    }
}

Upvotes: 1

Related Questions