jQuery插件范围建议

时间:2011-11-16 16:19:02

标签: jquery jquery-plugins

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

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

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

任何帮助都很受欢迎。

(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);

2 个答案:

答案 0 :(得分:1)

使用此:

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

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

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

答案 1 :(得分:1)

我可以建议使用jQuery Boilerplate吗?它是大多数插件开发的坚实基础,特别是如果您不熟悉范围的困难。

// 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/