0

假设我的模型非常简单(字符串列表),我不想将类型化的对象放入observableArray然后使用 deep validation对其ko.validation.init( { grouping: { deep: true } } )进行验证。

例如,我希望所有数组元素(它们是纯字符串)都符合minLength:3.

为什么ko.observable().extend({minLength:3})可以,但ko.observableArray().extend({minLength:3})不起作用?

除了将对象(而不是纯字符串)放入数组之外,还有其他解决方法吗?

小提琴.

4

1 回答 1

1

好吧,你可以像这样在原型上创建一个minLength函数:observableArray

ko.observableArray.fn.stringMinLength = function (minLength) {
    var self = this;// observableArray
    // Loop through array and apply logic to each element
    // Add subscriptions to the observableArray to determine what's been added (don't care about what's been removed)
    // In the subscriptions, deal with how to apply the minLength validation
    // -can't use '.extend({ minLength: minLength })' because these are plain strings, not observables
    return self;
}

现在你可以这样做了:

var oa = ko.observableArray(["foo", "bar", "bo"]).stringMinLength(3);

oa您的问题的症结在于,当' 的值发生突变时,您希望如何对所有字符串元素应用验证。

于 2013-09-10T19:30:14.770 回答