2011-04-12 33 views
1

我正在开发一个简单的jquery插件,并且在设置方法结构时遇到困难。有人可以请赐教。我正在使用官方Jquery Authoring文档中描述的插件结构。作为字符串返回的私有方法

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

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

回答

4

您必须调用带括号的函数methods._generateID()

+0

谢谢。这确实有效。但我也意识到了另一个问题。当我需要简单地返回我的Id时,函数返回this.each。我现在把它全部整理出来:)谢谢 – Sebastien 2011-04-12 09:50:22

+0

如果它有帮助,请标记为接受;)谢谢 – Headshota 2011-04-12 09:58:34

0

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

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

也许你的意思是:

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

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

+0

顺便说一句,它并没有返回“一个字符串”,但在某处输出'settings.id',输出机制是可视化函数引用。 – 2011-04-12 09:41:09

0

从你在哪里打来的。在插件内或从外面调用。

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

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

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

相关问题