如何在jquery插件默认值或选项中引用self

时间:2018-07-30 16:09:12

标签: javascript jquery plugins

我正在编写一个自定义jQuery插件,并且希望能够使用以下选项调用该插件:

  $(".my-class").myPlugin({
    source: $(this).find("img").attr("src"),
    target: $(this).find("<div class='testing'></div>")
  });

如何引用调用插件的$(".my-class"),以便可以在默认选项或指定选项中找到子代或其他元素?

这是插件:

(function (factory) {
  // CommonJS, AMD or browser globals
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'));
  } else {
    factory(jQuery);
  }
}(function ($) {
  const name = 'backgroundImage';
  const defaults = {
    // this doesnt work, but it's an example of what i want to do
    source: $(this).find("img").first().attr('src'),
    // same here
    target: $(this),
    styles: "center center / cover no-repeat",
    hide: true
  };

  function Plugin(el, options, selector) {
    this._name = name;
    this._defaults = defaults;
    this.el = el;
    this.$el = $(this.el);
    this.selector = selector;
    this.settings = $.extend({}, defaults, options);

    /*
     * Process and add data-attributes to settings as well for ease of use. Also, if
     * data-attributes is an object then use it as extra settings.
     */
    if (typeof(this.$el.data(name)) === 'object') {
      $.extend(this.settings, this.$el.data(name));
    }

    const attributes = {};
    const data = this.$el.data();
    Object.keys(data).forEach(function (key) {
      const value = data[key];
      key = key.replace(name, '');
      if (key !== '') {
        attributes[key.charAt(0).toLowerCase() + key.slice(1)] = value;
      }
    });

    $.extend(this.settings, attributes);

    this.init();
  }

  Plugin.prototype = {
    init: function () {
      const plugin = this;

      if (plugin.settings.source) {
        this.$el.css('background', 'url('+plugin.settings.source+')' + plugin.settings.styles);
      }

    }
  };

  $.fn[name] = function (options) {
    return this.each(function () {
      if (!$.data(this, 'plugin_' + name)) {
        $.data(this, 'plugin_' + name, new Plugin(this, options, this.selector));
      }
    });
  };

}));

我希望默认值引用调用插件的元素,并能够在调用插件时覆盖这些元素。

1 个答案:

答案 0 :(得分:0)

您可以将函数作为选项传递。

例如,在设置默认值时:

const defaults = {
  source: function (el) {return $(el).find('img').first().attr('src');},
  target: function (el) {return $(el);},
};

然后创建一个传递插件当前上下文的函数:

getTarget: function () {
  const plugin = this;

  // if its a function then pass it the current context
  if (typeof plugin.settings.target === 'function') {
    return plugin.settings.target(plugin.$el);
  } else {
    return $(plugin.settings.target);
  }
}

或从插件调用中覆盖时:

$('.element').myPlugin({
  source: function (el) {
    return $(el).find('img').first().attr('src');
  },
});