Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating "placeholder" attribute using knockout

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:

<input type="text"  name="contrasena" id="login-user" value="" placeholder="" data-bind="value: user">

I have a JSON to store the value a I want to use for "pass" keyword, and it works correctly.

I tried to set "placeholder" attribute using the same method, but it doesn't works:

<input type="text"  name="contrasena" id="login-user" placeholder="" data-bind="placeholder: user">

I tried to modify knockout.js file adding "ko.bindingHandlers['placeholder']" function based on "ko.bindingHandlers['value']" (modifying "placeholder" instead of "value" in "ko.jsonExpressionRewriting.writeValueToProperty" function), but it doesn't work correctly, it puts the information in "value" attribute instead of "placeholder".

Anyone knows the way to solve this?

Thank you very much!

like image 380
user1702964 Avatar asked Sep 28 '12 08:09

user1702964


2 Answers

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());
like image 108
gbs Avatar answered Oct 26 '22 02:10

gbs


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.

like image 37
Sethi Avatar answered Oct 26 '22 01:10

Sethi