使用自定义bindingHandler的文本输入水印

使用自定义bindingHandler的文本输入水印

本文介绍了使用自定义bindingHandler的文本输入水印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个自定义的BindingHandler,我可以使用它为文本输入字段赋予水印行为.

I've been trying to create a custom bindingHandler that i can use to give a watermark behaviour to text input fields.

通过watermark我的意思是:向文本字段添加默认值,这些文本字段将被焦点移开,如果文本字段仍为空,则在模糊时替换为默认值

By watermark i mean: to add default values to text fields that are removed on focus, and replaced on blur if the text field is still empty

我设法按照jsfiddle中的说明进行操作: http://jsfiddle.net/rpallas/nvxuw/

I have managed to get this to work as demonstrated in this jsfiddle: http://jsfiddle.net/rpallas/nvxuw/

关于此解决方案,我有3个问题:

I have 3 questions about this solution:

  1. 有什么方法可以更改它,以便只需要声明一次水印值?目前,我必须将其放在声明绑定的地方,并且还必须初始化可以在viewModel中以相同的值观察到-否则它将没有初始值.
  2. 是否存在一种更好的方法来获取元素值所绑定的基础可观察对象.我目前正在使用allBindingsAccessor来获取它,但这对我来说是错误的.最初,我只是使用jquery $(element).val('')设置值,但这也感觉不对.哪个最好,还是有更好的方法?
  3. 是否有人已经知道这个问题的现有解决方案?我是在重新发明轮子吗?
  1. Is there any way to change it so that I only have to declare the watermark value once? Currently I have to put it on the place where I declare the binding and I also have to initialise the observable with the same value in the viewModel - as it will otherwise have no initial value.
  2. Is there a better way of getting to the underlying observable that the elements value is bound to. I'm currently grabbing it using the allBindingsAccessor, but this feels wrong to me. Originally I was just setting the value using jquery $(element).val('') but this also felt wrong. Which is best, or is there a better way?
  3. Does any one have or know of an existing solution to this this problem? Am I re-inventing the wheel?

推荐答案

我认为您使用allbindings是不必要的.实际上,我认为水印根本不需要了解可观察到的东西,因为水印通常就是placeholder属性.

I think you're use of allbindings is unecessary. In fact I don't think the watermark needs to be aware of the observable at all since that's what a watermark generally does i.e the placeholder attribute.

这对您有用吗?

ko.bindingHandlers.watermark = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var value = valueAccessor(), allBindings = allBindingsAccessor();
        var defaultWatermark = ko.utils.unwrapObservable(value);
        var $element = $(element);

        setTimeout(function() {
            $element.val(defaultWatermark);}, 0);

        $element.focus(
            function () {
                if ($element.val() === defaultWatermark) {
                    $element.val("");
                }
            }).blur(function () {
                if ($element.val() === '') {
                    $element.val(defaultWatermark)
                }
            });
    }
};

http://jsfiddle.net/madcapnmckay/Q5yME/1/

希望这会有所帮助.

这篇关于使用自定义bindingHandler的文本输入水印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 16:17