I have a form with some fields getting some data using knockout.js (ver. 2.1.0). For example, to update the \"value\" field of an input I put:
You should use the existing attr binding, like this:
<input data-bind="attr: {placeholder: ph}" />
var Model = function () {
this.ph = ko.observable("Text...");
}
ko.applyBindings(new Model());
If you want to use data-bind="placeholder: user"
, you can create a custom-binding in your js code.
You were on the right path using ko.bindingHandlers['placeholder']
but you don't need to edit the knockout.js file -- in fact, that is bad practice.
This would require a very basic custom-binding:
ko.bindingHandlers.placeholder = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
ko.applyBindingsToNode(element, { attr: { placeholder: underlyingObservable } } );
}
};
For a guide on custom-bindings, see here
Although Knockout is itself inherently obtrusive, this is slightly less. It removes the knowledge of how the placeholder is applied to the element from the view.
In fact, if in the future you wanted to apply some sort of jQuery plugin to show placeholders in browsers which don't support the placeholder
attribute, this would be the place (init:
) to initialise the plugin -- you would also need an update:
function in that case.