jQuery插件范围建议



我目前正在编写我的第一个jQuery插件,我正在努力寻找一种合适的方法来构建代码。我已经阅读了jquery网站上的文档以及其他插件的源代码,但似乎找不到一种一致同意的方法来解决我遇到的问题。

插件将一些文本处理添加到文本输入元素中,将文本格式化为日期。

下面的例子将两个事件绑定到元素。我遇到的问题是如何从_processText函数访问元素本身。在这个例子中,我使用了$(this),但这给了我对象,而不是元素,所以我不能设置它的值或触发事件。我发现这样做的唯一方法是在bind事件中将元素作为参数直接传递到函数中,但我认为这看起来不正确。

非常感谢您的帮助。

(function($) {

    var methods = {
        init : function( options ) {
            return this.each(function() {

                // Process the entered text and convert
                // into a formatted date
                $(this).bind('blur', function(event){
                    methods._processText($(this).val());
                });

                // Custom event to trigger when invalid text
                // is entered
                $(this).bind('invalid', function(event) {
                    alert("Invalid");
                });

            });
        },
        _processText: function(txt) {
            // Sudo code
            if (txt.isValid()) {
                $(this).val(txt)
            } else {
                $(this).trigger("invalid");
            }
        }
    };



    // boilerplate
    $.fn.datefield = 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.DateField' );
        }
    };
})(jQuery);

使用

methods._processText.call(this, $(this).val());

然后在_processText方法中,this将指向jQuery对象。

参考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

我可以建议使用jQuery样板吗?对于大多数插件开发来说,这是一个非常坚实的基础,尤其是当你不熟悉作用域的困难时。

// the semi-colon before function invocation is a safety net against concatenated 
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {
    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.
    // window and document are passed through as local variables rather than globals
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).
    // Create the defaults once
    var pluginName = 'defaultPluginName',
        defaults = {
            propertyName: "value"
        };
    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;
        // jQuery has an extend method which merges the contents of two or 
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and the options via the instance, 
        // e.g., this.element and this.options
    };
    // A really lightweight plugin wrapper around the constructor, 
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
            }
        });
    }
})( jQuery, window, document );
http://jqueryboilerplate.com/

最新更新