2013-01-04 42 views
1

我正在寫一個jQuery插件來對錶單字段進行正則表達式驗證。這是我寫的第一個jQuery插件,我發現許多不同的教程和插件設計模式令人困惑。重構jQuery插件

我都忍了的我目前在這裏http://jsfiddle.net/WpvMB/

以及物品是否完整在這些地方工作的樣品我的插件代碼(充滿雖然它的工作就是我假設是可怕的設計決定)

(function($){ 

    var settings = {} 

    var methods = { 
    init : function(options) { 

     settings = $.extend({ 
     'error_class': 'error', 
     'success_class': 'success', 
     'regex': /.*/, 
     }, options); 

     this.bind('keyup focusout focusin', methods.doValidate); 
    }, 

    valid : function() { 
     if ($(this).val().match(settings.regex)) { 
     return true 
     } 
     return false 
    }, 

    doValidate: function() { 
     if ($(this).regexField('valid')) { 
     $(this).addClass(settings.success_class) 
     $(this).removeClass(settings.error_class) 
     } else { 
     $(this).removeClass(settings.success_class) 
     $(this).addClass(settings.error_class) 
     } 
    }, 

    }; 

    $.fn.regexField = function(method) { 

    if (methods[method]) { 
     return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.regexField'); 
    }  

    }; 

})(jQuery); 

理想情況下,我希望插件能夠像現在一樣運行,並且還能夠調用元素上的有效方法並接收真/假結果,例如。

$('#textinput').regexField({'regex': /^[0-9]+$/}) 
$('#textinput').valid() 
>>> true 

在什麼特定插件圖案是適合於這種類型的插件是非常讚賞爲是對現有代碼,關於任何反饋任何輸入。

+0

你想這樣的事情? http://jsfiddle.net/ZeKxk/ –

+0

最後我用jQuery widget工廠。這看起來更直截了當。 – justinfay

回答

1

添加這個插件裏面,當你希望它會工作:

$.fn.valid = function() { 
    return $(this).regexField("valid"); 
} 
+0

謝謝你,但是我現在意識到做這樣的事情是壞的,壞的,壞的,因爲它混亂了jQuery命名空間。我想更好的方法是 $('#inp')。regexField('valid') 感謝您的幫助。 – justinfay

+0

不客氣。 –