如何使用插件方法创建Jquery插件并保持可链接性?

时间:2012-11-21 21:27:29

标签: javascript jquery jquery-ui jquery-plugins

我正在尝试创建一个Jquery插件,它保持可链接性并具有Jquery Plugins/Authoring中指定的公共方法。复杂性在于它试图维护我希望公共方法使用的某些变量。

这是我的jsfiddle:http://jsfiddle.net/badmash69/9cqcj/2/

javascript code :

(function($){

  var methods = {
    init : function( options ) {
      this.options = options;
    }
  , add_that: function (elem) {

      $(this).append(elem);
      return (this);
    }
  , show_parent: function(){
      // this is a simple test to see if the plugin vars are accessible
      alert("parent id=" + $(this).parentId)
    }              
  , add_this: function (elem) {
      return methods.add_that.apply(this,elem);
    }
  };

  $.fn.test = function (method) { 
        var args = method;
        var argss = Array.prototype.slice.call(args, 1);      


      return this.each(function(){

          var $this = $(this);
          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.test' );
    }          


          var element = $(this);
          var parentId= element.parent().attr("id")

      });       


  };

})(jQuery);

$('#test').test('add_this',$('<div>Hello World d</div>'));

$('#test').test('show_parent');
​

Html代码

<div id="holder">
<div id="test"></div>
</div>  

我无法弄清楚我在这里做错了什么。 我怎样才能使它工作?我非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我这样做的方式是使用$ .data,你可以使用特定的对象本地变量,“公共”/“私有”方法等等。这里我将如何做一个小例子

(function($){
      var myTestMethods = function() {
          // local variables
          var last_added;

          // local "private" methods 
          var init=function(options) {
              this.options = options;
              last_added = null;
              return this;
          };

          var add_that=function(elem) {
              last_added = elem;
              this.append(elem);
              return this;
          };

          var show_parent=function() {
              alert("parent id=" + this.parent().attr('id'));
          }

          return { // this are your obj "public" methods
                 // notice we are not listing add_that method, therefore this method will be a "private" method
            init : init,
            show_parent: show_parent, // you can publish a private method
            get_last_added: function(){
              return last_added; // you can access local variables
            }, 
            add_this: function (elem) {
              return add_that.apply(this, elem);  // you can also run local methods
            }
          }
      };

      $.fn.test = function (method) {
          var obj_data = this.data('myTestData');
        if (typeof(obj_data) != "undefined") {
          if ( obj_data[method] ) {
            return obj_data[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
          }else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.test' );
          }
        } else {
          if (typeof(method) === 'object' || ! method) {
            obj_data = myTestMethods();
            this.data('myTestData', obj_data);
            return obj_data.init.apply(this, arguments);
          }
        }
      };

    })(jQuery);

    $('#test').test(); //init

    $('#test').test('add_this',$('<div>Hello World d</div>'));
    $('#test').test('show_parent');

此代码的测试很少,因此可能存在小错误,但这会向您展示如何做您想要的基本想法。

答案 1 :(得分:0)

看一下这个演示:http://jsfiddle.net/9cqcj/11/

根据他们的建议,要保留数据,最好使用.data

      return this.each(function(){          
          var $this = $(this);
          $this.data("parentId",$this.parent().attr("id"));
....

(假设你需要集合中每个元素的parentId)

此外,您在调用方法时遇到问题:

 return this.each(function(){

          var $this = $(this);
          if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));

最后一行arguments - 使用传递给.each的函数的参数。为了获得原始参数,在调用方法之前将它们保存到变量中:

$.fn.test = function (method) { 
        var args = arguments;      
      return this.each(function(){          
          var $this = $(this);
          $this.data("parentId",$this.parent().attr("id"));
          if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( args , 1 ));

请参阅最后一行中用args替换的参数。

此外,当您使用.apply时,第二个参数应为数组:

return methods.add_that.apply(this, [elem]);

如果是这样的话:

return methods.add_that.apply(this, elem);

您可能会遇到意外问题。例如,尝试用简单的字符串elem替换"test",看看你将在控制台中获得什么。或者如果你将传递jQuery对象,你将在被调用的方法

中获得DOM对象