updating “placeholder” attribute using knockout

空扰寡人 提交于 2019-11-30 04:40:27

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.

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