Check If Passed Element Is Already Initialized Return Its Instance Javascript Plugin
Plugin code: ( function() { this.Modal = function modal( selector, options ) { // If there's a passed element is already initialized return its instance if ( !m
Solution 1:
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 = newMap();
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 optionsvar defaults = {
open: false
};
this.options = extendDefaults(defaults, options);
element.style.setProperty('background-color', 'red');
}
functionextendDefaults(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 = newModal(this);
});
// we will use already careated instances here, see the console.log
$('.button').each(function() {
var myPlugin = newModal(this);
});
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonclass="button">First Button</button><buttonclass="button">Second Button</button><buttonclass="button">Third Button</button>
Post a Comment for "Check If Passed Element Is Already Initialized Return Its Instance Javascript Plugin"