在jQuery插件中调用原型中的函数

时间:2013-05-26 14:48:17

标签: javascript jquery jquery-plugins

尝试学习可扩展的jQuery插件开发。我完全不知道如何从jQuery插件包装器中调用类中的函数。

我主要是从here为我的代码创建了包装器,并尝试了解/使用this,但没有太多运气。

以下代码的重要部分。我喜欢它所以我可以调用(例如)$(something).carousel(5)并将它传递给Carousel类中的slide函数。对于字符串也是如此,因此$(something).carousel('go')将在类中运行go

如何使用此结构执行此操作?

(function(window, $){

  var Carousel = function(elem, options){
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
  };

  Carousel.prototype = {

    defaults: {
     [...]
    },

    init: function() {
      this.config = $.extend({}, this.defaults, this.options);
      this.create();
      return this;
    },
    create: function() {
       [...]
    },
    slide: function(num) {
       [...]
    }
  };

  Carousel.defaults = Carousel.prototype.defaults;

  $.fn.carousel = function(options) {
    return this.each(function() {

      var carousel = new Carousel(this, options);
      if (!options || typeof options == 'object') carousel.init();
      else if (typeof options == 'number') carousel.slide(options);
      else if (typeof options == 'string') carousel.options;

    });
  };

  window.Carousel = Carousel;

})(window, jQuery);

1 个答案:

答案 0 :(得分:1)

您或多或少走在正确的轨道上,主要问题是调用carousel.options只会访问options个实例的Carousel属性。你想要做的是动态调用实例上的函数:

 $.fn.carousel = function(options) {
    return this.each(function() {

      var carousel = new Carousel(this, options);

      // do a loose comparison with null instead of !options; !0 == true
      if (options != null || typeof options === 'object')
        carousel.init();
      else if (typeof options === 'number')
        carousel.slide(options);
      // make sure options is the name of a function on carousel
      else if (typeof options === 'string' && typeof carousel[options] === 'function') {
        carousel[options](); // call the function by name
      }

    });
  };
相关问题