【问题标题】:Private method returned as string私有方法返回为字符串
【发布时间】:2011-04-12 09:32:12
【问题描述】:

我正在开发一个简单的 jquery 插件,但在设置方法结构时遇到了困难。有人可以启发我。我正在使用官方 Jquery Authoring 文档中描述的插件结构。

我遇到的问题是在调用私有函数 _generateID 时,该函数实际上返回函数文本 (function() { return this.. ) 而不是 'hi'。

(function( $ ){

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

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('<div>', {
                    id : settings.id,
                }).appendTo(this);              
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = 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.workzone' );
        }    
    };

})( jQuery );

【问题讨论】:

    标签: jquery plugins methods


    【解决方案1】:

    你必须用括号methods._generateID()调用函数。

    【讨论】:

    • 谢谢。这确实有效。但我也意识到了另一个问题。当我需要简单地返回我的 ID 时,该函数正在返回 this.each。我现在把一切都整理好了:) 谢谢
    【解决方案2】:

    你在哪里调用函数?我只看到:

    var settings = {
       'id' : methods._generateID,
    };
    

    也许你的意思是:

    var settings = {
       'id' : methods._generateID(),
    };
    

    函数调用形式为return_value = function_name(arg_list);

    【讨论】:

    • 顺便说一句,它没有返回“字符串”,而是在您输出 settings.id 的地方,输出机制正在可视化函数引用。
    【解决方案3】:

    从您拨打电话的地方。在插件内或从外部调用。

    Headshota 的 answer 用于调用插件中的方法。

    $('div').pluginName('_generateID', arg0, arg1, ...); //Way to call a plugin method from outside out side plugin and pass arguements.
    

    请注意,将方法名称作为第一个字符串参数传递,然后是其他参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2020-04-13
      • 2023-03-30
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多