我知道的JavaScript -- 设计模式(桥接)应用之 – 验证器
引子:
首先请各位同学跟我来一起复习设计模式中的桥接模式(Bridge), 废话不多言表直接上图:
在这个设计模式中我们的抽象类和实现类可以各自进行扩展和封装这样就可以对它们进行脱耦, 通过组合来产生很多变化。这种思想也符合“少用继承,多用组合”的设计原则.在桥接模式中我们可以用Abstraction 类来对实现类(ConreteImplementor)和修正抽象化类(RefinedAbstraction)进行桥接。但JavaScript 如何实现桥接呢?Please follow me
1 //Validation类:
2
3
4 Validation= {
5 required: function(elem) {
6 return!$(elem).val().trim().isNullOrEmpty();
7 },
8 email: function(elem) {
9 returnValidation.regexValidator($(elem).val().trim(),Validation.Regex.email);
10 },
11 regexValidator: function(elemVal, /*string*/regex,) {
12 if(!elemVal.isNullOrEmpty() && !(elemVal.match(regex, "\g"))) {
13 returnfalse;
14 } else{
15 returntrue;
16 };
17 },
18 Regex: {
19 email:/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)?$/
20 }
21 };
22 Validation.validateColl= {
23 'jq-validation-required': {validFunc:Validation.required, ErrMsg: 'Required'},
24 'jq-validation-email': {validFunc:Validation.email, ErrMsg: 'Invalid email address'}
25 };
26 Validator类:
27
28
29 (function () {
30 varvalidator_elements_blur_selector = 'input[type="text"]';
31 varvalidator_elements_change_selector = 'select,input[type="hidden"]';
32 var validator_elements_selector =validator_elements_blur_selector + ',' +validator_elements_change_selector;
33
34 Validator = function(validateScopeSelector) {
35 this._validateColl= $.extend(true, {}, Validation._validateColl);
36 this._validateDom= $(validateScopeSelector);
37 vartheValidator = this;
38 this._validateDom.delegate(validator_elements_blur_selector,'blur',function() {
39 theValidator.validateInput(this, 'blur');
40 });
41 this._validateDom.delegate(validator_elements_change_selector,'change', function() {
42 varinputValidated = theValidator.validateInput(this,'change');
43 });
44 };
45
46 Validator.prototype = {
47 validate: function() {
48 varvalidated = true;
49 vartheValidator = this;
50 $(validator_elements_selector, this._validateDom).each(function() {
51 if(!theValidator.validateInput.call(theValidator, this)) {
52 validated = false;
53 };
54 });
55 returnvalidated;
56 },
57 validateInput: function(elem, event) {
58 varinput = $(elem);
59 varclassArr = input.attr('class').split('');
60
61 varvalidated = true;
62 varinValidTable = new Hashtable();
63 for(var i = 0; i < classArr.length; i++) {
64 varclassItem = classArr[i];
65 if(!classItem.startWith('jq-validation')) continue;
66 varvalidateItem = this._validateColl[classItem];
67 if(validateItem && validateItem.validFunc) {
68 if(!validateItem.validFunc(input, validateItem)) {
69 validated = false;
70 if (!strPopupErr.isNullOrEmpty()) {
71 strPopupErr += "";
72 }
73 inValidTable.add(classItem, validateItem);
74 &nbs
补充:web前端 , JavaScript ,