问题
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