检查传递的元素是否已经初始化,返回其实例javascript插件 [英] Check if passed element is already initialized return its instance javascript plugin

查看:45
本文介绍了检查传递的元素是否已经初始化,返回其实例javascript插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

插件代码:

( function() {
    this.Modal = function modal( selector, options ) {
        // If there's a passed element is already initialized return its instance
        if ( !modal.instances ) {
            modal.instances = {};
        }
        if ( modal.instances[ selector ] ) {
            return modal.instances[ selector ];
        }
        modal.instances[ selector ] = this;

        // Plugin options
        var defaults = {
            open: false
        };
        this.options = extendDefaults( defaults, options );
        selector.style.setProperty( 'background-color', 'red' );
    }

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

要运行插件:

$( window ).on( 'load', function() {
    $( '.button' ).each( function() {
        var myPlugin = new Modal( this );
    } );
} );

HTML代码:

<button class="button">First Button</button>
<button class="button">Second Button</button>
<button class="button">Third Button</button>

代码上的错误,即第一个按钮仅会读取插件并获得红色背景,第二个和第三个按钮将返回第一个按钮的实例,而且我不知道为什么发生这种情况,按钮具有相同的功能类,是的,但是有不同的元素.

The wrong on the code that the first button only will read the plugin and gets the red background and the second and third buttons will return the instance of the first button, And I don't why this happens the buttons has the same class, yes but there are different elements.

我需要从插件调用的每个按钮都具有红色背景色,同时避免多次初始化(如果传递的元素已经初始化,则返回其实例).

I need every button called from the plugin gets the red background color and at the same time avoid initialized multiple times (If the passed element is already initialized return its instance).

推荐答案

好.问题在于这里的对象方法是因为对象的键只能是字符串.当我们试图像这样 modal.instances [选择器] = this; 时,我们实际上将拥有这个 modal.instances ['[object HTMLButtonElement]'] = this; 地图方法,因为地图的键可以是一个对象.

Ok. The problem is in objects approach here because the keys of the object can be only strings. And when we are trying to so smth like this modal.instances[ selector ] = this; we actually will have this modal.instances['[object HTMLButtonElement]'] = this; for any of the html button element. So the solution is to use Map approach, because the keys of the map can be an objects.

(function() {
  const modalInstances = new Map();

  this.Modal = function(element, options) {
    if (modalInstances.has(element)) {
      console.log('return instance for: ' + element.innerHTML);
      return modalInstances.get(element);
    }

    modalInstances.set(element, this);

    // Plugin options
    var defaults = {
      open: false
    };
    this.options = extendDefaults(defaults, options);
    element.style.setProperty('background-color', 'red');
  }

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

$(window).on('load', function() {
  $('.button').each(function() {
    var myPlugin = new Modal(this);
  });
  
  // we will use already careated instances here, see the console.log
  $('.button').each(function() {
    var myPlugin = new Modal(this);
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="button">First Button</button>
<button class="button">Second Button</button>
<button class="button">Third Button</button>

这篇关于检查传递的元素是否已经初始化,返回其实例javascript插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆