【发布时间】:2013-04-16 02:49:57
【问题描述】:
我有以下类可以验证名称并且不允许用户输入空名称。有了它,我可以获得有效值并在输入无效时通知用户(保留最后一个好的值)。
class @Person
constructor: (name) ->
@name = ko.observable name
@nameLastInvalid = ko.observable false
@nameAttempt = ko.computed
read: @name
write: (value) =>
if value.length > 0
@name value
@nameLastInvalid false
else
@nameLastInvalid true
owner: @
我想让相同的功能更可重用。有没有办法扩展 ko.observable 对象以添加 'lastInvalid' 和 'attempt' 方法?
类似:
class @Person
constructor: (name) ->
@name = ko.observable(name).extend({ required: true })
然后就可以做到:
person.name()
person.name().lastInvalid()
person.name().attempt()
AFAIK knockout-validation 不能这样工作。它允许您输入无效值,然后告诉您它是否有效。
更新:
我添加了以下扩展程序,但它似乎没有做任何事情(我得到 name.attempt is undefined)
ko.extenders.required = (target, option) ->
target.lastInvalid = ko.observable false
target.attempt = ko.computed ->
read: target
write: (value) ->
if value.length > 0
target value
target.lastInvalid false
else
target.lastInvalid true
target
【问题讨论】:
标签: javascript knockout.js coffeescript knockout-validation