根据所有可观察的值自动修剪空白 [英] Automatically trim whitespace from all observable values

查看:60
本文介绍了根据所有可观察的值自动修剪空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Knockout中有一个ViewModel,该ViewModel主要来自于映射插件(即,动态地).这很好.但是,现在我的客户希望我确保在提交给服务器之前,所有输入的空白​​都已修剪掉.显然,修整代码非常简单,但是对于Knockout来说相对较新,因此我不确定将代码放置在何处.我读到有关扩展器的信息,但是回头再将其添加到每个可观察对象中似乎很冗长和重复.另外,我什至不确定我是否可以对动态生成的可观察对象(la,映射插件)执行此操作.

I have a ViewModel in Knockout that is derived mainly from the mapping plugin (ie, dynamically). This works fine. However, now my client wants me to make sure that all inputs have whitespace trimmed off before submitting to the server. Obviously, the trimming code is very simple, but being relatively new to Knockout, I'm not sure exactly where to put this code. I read about extenders, but that seems pretty verbose and repetitive to go back and add that to each observable. Plus I'm not even sure I can do that to dynamically generated observables (a la, the mapping plugin).

是否有任何我可以扩展/覆盖的中央机制,以便在每次可观察到的更改时都可以注入一些修整代码?基本上,我试图避免花大量时间浏览所有表单并添加如果不需要,可以在HTML中使用特殊的绑定语法.

Is there any central mechanism I can extend/override where I can inject some trimming code every time an observable changes? Basically I'm trying to avoid hours spent going through all of our forms and adding special binding syntax in the HTML if I don't have to.

谢谢.

推荐答案

我遇到了同样的问题.我写了一个扩展,因此您可以在视图模型中调用trimmed,而无需更改绑定.例如:

I had the same problem. I wrote an extension so you can call trimmed in your view-model without having to change your bindings. For example:

var vm = {
    myValue: ko.observable('').trimmed()
}

扩展名:

ko.subscribable.fn.trimmed = function() {
    return ko.computed({
        read: function() {
            return this().trim();
        },
        write: function(value) {
            this(value.trim());
            this.valueHasMutated();
        },
        owner: this
    });
};

代码在JSFiddle上

Code is on JSFiddle with examples.

这篇关于根据所有可观察的值自动修剪空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆