簡體   English   中英

純Javascript插件開發

[英]Pure Javascript plugin development

我需要開發一個純JavaScript插件,可以像jquery類型的插件( $('.pluginWrapper').pluginInit();一樣進行訪問$('.pluginWrapper').pluginInit();

但是我需要使用純JavaScript,我在想也許支持2種格式:

document.getElementById('pluginWrapper').pluginInit();
pluginInit(document.getElementById('pluginWrapper'));

我知道您必須做一個IIFE來包裝它並通過對象方法調用它,但是我不知道如何將它綁定到一個元素上。

我是說我是一個初學者,所以請有人可以解釋一下。 干杯!

您將更安全地開發一個插件接口,該接口僅將插件公開為以元素為參數的函數。

function MyPlugin(element) {
  // do stuff with element
  element.setAttribute('data-plugin-id', 'pluginName');
}

另一種方法涉及擴展Element.prototype 這可能是生產軟件中的危險動作

但是,仍有可能。

Element.prototype.pluginInit = function() {
  // the element is accessible as `this`
  this.setAttribute('data-plugin-id', 'pluginName');
}

每個人都易於理解的功能。 插件編寫者不必了解用於創建和注冊插件的任何接口,他們只需要知道他們應該編寫將元素作為參數的函數即可。

Rich Hickey(Clojure的創建者)有一個很棒的演講,名為Simplicity Matters ,他強調說,您可以做的最壞的事情是,當簡單的解決方案可用時,會增加額外的復雜性。

在這種情況下,除了將元素作為參數的函數之外,您不需要任何其他復雜的事情。


如果必須完全控制該功能,則可以編寫一個簡單的界面來注冊和啟動插件。

function Plugin(element) {
  if(element === null) {
    throw new TypeError("Element must not be null!");
  }

  // get all the plugin names from the store
  var pluginNames = Object.keys(Plugin.store);

  // make sure `this` is set to the element for each plugin
  var availablePlugins = pluginNames.reduce(function(plugins, name) {
    plugins[name] = Plugin.store[name].bind(element);
    return plugins;
  }, {});

  // return an object containing all plugins
  return availablePlugins;
}

// we'll store the plugins in this object
Plugin.store = {};

// we can register new plugins with this method
Plugin.register = function(name, pluginFn) {
  Plugin.store[name] = pluginFn;
};

您可以這樣使用。

Plugin.register('myPlugin', function() {
  this.setAttribute('data-plugin-id', 'myPlugin');
});

Plugin(document.getElementById('pluginWrapper')).myPlugin();

如果您希望插件函數采用選擇器(與jQuery相同),則可以在您的Plugin定義內使用document.querySelectorAll

function Plugin(selector) {
  var element = document.querySelectorAll(selector);

  if(element === null) {
    throw new TypeError("Element must not be null!");
  }

  // get all the plugin names from the store
  var pluginNames = Object.keys(Plugin.store);

  // make sure `this` is set to the element for each plugin
  var availablePlugins = pluginNames.reduce(function(plugins, name) {
    plugins[name] = Plugin.store[name].bind(element);
    return plugins;
  }, {});

  // return an object containing all plugins
  return availablePlugins;
}

然后,您可以像這樣使用它。

Plugin.register('myPlugin', function() {
  this.setAttribute('data-plugin-id', 'myPlugin');
});

Plugin('#pluginWrapper').myPlugin();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM