Knockout wrap value binding

天涯浪子 提交于 2019-12-23 12:26:53

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/18015501/knockout-wrap-value-binding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!