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

标签 javascript jquery jquery-ui jquery-plugins

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

这是我的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>  

我不知道我在这里使用了哪些兴奋剂。 我怎样才能让它发挥作用?我将非常感谢任何帮助。

最佳答案

我这样做的方式是使用 $.data,您可以拥有特定的对象本地变量、“公共(public)”/“私有(private)”方法等。这里有一个小例子,说明我将如何做到这一点

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

此代码进行了小型测试,因此可能存在小错误,但这将向您展示如何做您想做的事情的基本想法。

关于javascript - 如何使用插件方法创建 Jquery 插件并保持可链接性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502316/

相关文章:

javascript - 在组合悬停状态和单击缩放功能时遇到问题(fitToBounds?)

javascript - observablearray 中的对象 KnockoutJs

javascript - 下拉导航/排序 dd 与按钮对齐

javascript - 如何在 MVC 4 中设置时间选择器

javascript - Jquery-UI 可排序列表不能很好地处理 Meteor 模板中的响应式(Reactive)更新

javascript - 为什么会出现此错误 - "TypeError: ... is not a constructor"

javascript - 显示/隐藏 div(如果包含/不包含单选按钮值文本)

javascript - 如何使用 HTML 5 日期输入增加月份 - 将结果输出到 DOM

php - 在 <img> 标签中显示以 # 开头的图像

Jquery UI - jquery 可调整大小的边距问题