避免为同一个选择器多次调用同一个 javascript 插件

Avoid calling same javascript plugin multiple time for the same selector

这是我的插件代码:

( function() {
    this.Modal = function( selector, options ) {
        // Define option defaults 
        var defaults = {
            open: false
        }

        this.options = extendDefaults( defaults, options );

        alert();
    }

    function extendDefaults( source, properties ) {
        var property;
        for ( property in properties ) {
            if ( properties.hasOwnProperty( property ) ) {
                source[ property ] = properties[ property ];
            }
        }
        return source;
    }
}() );

简单地说,我需要一种方法来防止再次为已经调用过的 SAME 选择器调用插件。

更清楚的是,如果我尝试通过这样做来初始化插件:

var firstSeelctor = new Modal( '.button' );
var secondSeelctor = new Modal( '.button' );

我需要调用第一个并忽略第二个,因为它已经在第一个中调用了相同的选择器。

您需要将选择器存储在您已经创建的某处(直接在函数构造函数中,例如),然后在每次创建实例时检查它。

(function() {
  this.Modal = function modal(selector, options) {
    if (!modal.instances) {
      modal.instances = {};
    }

    if (modal.instances[selector]) {
      return modal.instances[selector];
    }

    modal.instances[selector] = this;

    var defaults = {
      open: false
    };

    this.options = extendDefaults(defaults, options);
    console.log('created for selector: ' + selector);
    // alert();
  }

  function extendDefaults(source, properties) {
    var property;
    for (property in properties) {
      if (properties.hasOwnProperty(property)) {
        source[property] = properties[property];
      }
    }
    return source;
  }

  var firstSeelctor = new Modal('.button');
  var secondSeelctor = new Modal('.button');
  var thirdSeelctor = new Modal('.button-2');
  
  console.log(firstSeelctor === secondSeelctor); // true, because it's the same instances
}());