updating “placeholder” attribute using knockout

▼魔方 西西 提交于 2019-11-29 01:54:47

问题


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!


回答1:


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.




回答2:


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());


来源:https://stackoverflow.com/questions/12636695/updating-placeholder-attribute-using-knockout

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