扩展基类属性

时间:2014-10-15 00:27:50

标签: javascript knockout.js

如何在knockout.js中扩展基类'class'的属性?

我正在尝试在我的视图模型中设置敲除验证,但除非我的“子类”具有也是extended的可观察对象,否则它不起作用。请参阅以下代码段中的评论:

// setup knockout validation
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true
});

// base 'class'
function userAddressModelBase(data) {
    var self = this;
    self.firstName = ko.observable(data.firstName);
    self.lastName = ko.observable(data.lastName);
}

userAddressModel.prototype = new userAddressModelBase({});
userAddressModel.constructor = userAddressModel;

// 'sub-class'
function userAddressModel(data) {
    var self = this;

    userAddressModelBase.call(self, data);
    
    // extend 'base-class' properties; this doesn't work unless the current 'sub-class' also has an observable who is also extended...
    self.firstName.extend({ required: true });
    self.lastName.extend({ required: true });
    
    // the above statement only starts working if I extend an observable from this `sub-class`
    self.city = ko.observable();//.extend({ required: true });
    
    self.errors = ko.validation.group(self);
    
    self.validate = function() {
        
        console.log(self.errors().length);
        if (self.errors().length > 0) {
            self.errors.showAllMessages();
            return;
        }
    };
}

var model = new userAddressModel({ firstName: "Ted" });

ko.applyBindings(model);
.validationMessage{
    color: #ea033d;
    font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
    <label>First Name: <input type="text" data-bind="value: firstName" /></label><br>
    <label>Last Name: <input type="text" data-bind="value: lastName" /></label><br>
    <label>City: <input type="text" data-bind="value: city" /></label><br>
    <button data-bind="click: validate">Validate</button>
</div>

1 个答案:

答案 0 :(得分:-1)

执行继承的推荐方法是使用ko.utils.extend(self, new userAddressModelBase(data));

function userAddressModelBase(data) {
    var self = this;

    self.firstName = ko.observable(data.firstName);
    self.lastName = ko.observable(data.lastName);
}

下面我使用extend将所需的验证添加到firstName和lastName。

function userAddressModel(data) {
    var self = this;

    ko.utils.extend(self, new userAddressModelBase(data))
    self.firstName.extend({ required: true });
    self.lastName.extend({ required: true });
};

现在,在示例中,如果删除firstName然后退出文本框,则可以看到显示所需的消息。

http://jsfiddle.net/d4vLqkx2/1/