修剪可观察的空格

时间:2014-03-27 22:22:53

标签: knockout.js

我需要修剪所有可观测量。没有html绑定怎么做? 我试过Automatically trim whitespace from all observable values,但它对我不起作用。 我使用淘汰版3.0.0并且我使用了最新的chrome和最新的ie。

<div class="editor-label">
    <b>Name: </b>
</div>
<div class="editor-field">
    <input data-bind='value: name, valueUpdate: "afterkeydown"' placeholder="Enter name" /><br />
    <span style="font-weight:bold" data-bind="text: name"></span>
</div><br />

<div class="editor-label">
    <b>Age: </b>
</div>
<div class="editor-field">
    <input data-bind='value: age, valueUpdate: "afterkeydown"' placeholder="Enter age" /><br />
    <span style="font-weight:bold" data-bind="text: age"></span>
</div>


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

if (!String.prototype.trim) {
    String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); };
}

var ViewModel = function () {
    var self = this;
    self.name = ko.observable().extend({ required: true }).trimmed();
    self.age = ko.observable().extend({ required: true }).trimmed();
};

ko.applyBindings(new ViewModel());

异常:对象不支持属性或方法'trimmed'

0 个答案:

没有答案