Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout wrap value binding

Tags:

knockout.js

I am using mathias bynen's placeholder code and I wanted to use it along with knockout, if I do a simple custom binding like this:

ko.bindingHandlers.placeholder = {
    init: function (element) {
        $(element).placeholder();
    }
};

and the html

<input placeholder = "Line 1" data-bind="placeholder: {}, value: addressLine1">

It works, but I would like to "merge" them into one custom binding, for using it like

<input placeholder = "First Name" data-bind="placeholderValue: firstName">

So I tried this code:

ko.bindingHandlers.placeholderValue = {
    init: function (element, valueAccessor) {
        $(element).placeholder();
        ko.bindingHandlers.value.init(element, valueAccessor);
    },
    update: function (element, valueAccessor) {
        ko.bindingHandlers.value.update(element, valueAccessor);
    }
};

but it raises me an

Uncaught TypeError: undefined is not a function 

I'm not really getting the grip of ko yet

like image 648
mitomed Avatar asked Dec 15 '22 07:12

mitomed


1 Answers

When you are creating a delegating custom binding as a best practice you should always pass all the arguments of the init and update to the inner bindings, because you can never know what parameters the inner binding uses:

ko.bindingHandlers.placeholderValue = {
    init: function (element, valueAccessor, allBindingsAccessor, 
                    viewModel, bindingContext) {
        $(element).placeholder();
        ko.bindingHandlers.value.init(element, valueAccessor, 
             allBindingsAccessor, viewModel, bindingContext);
    },
    update: function (element, valueAccessor, allBindingsAccessor, 
                     viewModel, bindingContext) {
        ko.bindingHandlers.value.update(element, valueAccessor, 
             allBindingsAccessor, viewModel, bindingContext);
    }
};

You have got the exception because the init of the value biding uses the allBindingsAccessor parameter but because you haven't passed that in it raises the exception.

like image 140
nemesv Avatar answered Jan 30 '23 10:01

nemesv