简体   繁体   English

jQuery - 插件方法调用

[英]jQuery - plugin methods call

I'm trying to create a jQuery plugin following some official best practices 我正在尝试按照一些官方最佳实践创建一个jQuery插件

(function($){

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

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

})(jQuery);

I'd like the method add_that to be able to append things to the matched element(s). 我想方法add_that能够将东西附加到匹配的元素。
Now this method is called from add_this . 现在从add_this调用此方法。

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

TypeError: this.append is not a function TypeError:this.append不是函数

Why can't I access to the plugin ( this ) from add_that ? 为什么我不能从add_that访问插件( this )?

Because the scope has changed when you've called it from add_this . 因为当您从add_this调用范围时,范围已更改。 Notice that the original call used Function.apply to scope the call to this . 请注意,原始调用使用Function.apply来调用this范围。

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

So you can presumably get around the issue by using apply again in your method: 所以你可以通过在你的方法中再次使用apply来解决这个问题:

add_this: function (elem) {
  return methods.add_that.apply(this,[elem]);
}

Live example: http://jsfiddle.net/XaUHV/ 实例: http//jsfiddle.net/XaUHV/

In the context you're using it "this" refers to methods.add_that 在您使用它的上下文中,“this”指的是methods.add_that

Since methods.add_that is a function there is no method on it called "append" by default. 由于methods.add_that是一个函数,因此默认情况下没有任何方法称为“append”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM