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

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

问题描述

我在 Knockout 中有一个 ViewModel,它主要来自映射插件(即动态).这工作正常.但是,现在我的客户希望我确保在提交到服务器之前所有输入都被修剪掉了.显然,修剪代码非常简单,但是对于 Knockout 来说相对较新,我不确定将这些代码放在哪里.我读到了关于 extenders 的内容,但这似乎非常冗长和重复,要返回并将其添加到每个 observable.另外,我什至不确定我是否可以对动态生成的 observables(也就是映射插件)这样做.

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 上的示例.

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

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