All files / js/utils component.js

40.91% Statements 9/22
17.65% Branches 3/17
50% Functions 2/4
40.91% Lines 9/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67              1x   1x     1x 1x                                       1x 1x       1x   1x                       1x                            
import EventEmitter from './events';
import * as dom from './dom';
import * as types from './type';
import * as utils from './index';
 
export default class Component extends EventEmitter {
	constructor(element, options = {}, defaultOptions = {}) {
		super();
 
		this.element = types.isString(element) ? document.querySelector(element) : element;
 
		// An invalid selector or non-DOM node has been provided.
		Eif (!this.element) {
			throw new Error(`An invalid selector or non-DOM node has been provided for ${this.constructor.name}.`);
		}
 
		this.element[this.constructor.name] = this.constructor._interface.bind(this);
		this.element[this.constructor.name].Constructor = this.constructor.name;
		this.id = utils.uuid(this.constructor.name + '-');
 
		this.options = {
			...defaultOptions,
			...options,
			...dom.optionsFromDataset(this.element, defaultOptions) // Use Element dataset values to override options
		};
	}
 
	/**
	 * Initiate all DOM element corresponding to selector
	 * @method
	 * @return {Array} Array of all Plugin instances
	 */
	static attach(selector = null, options = {}) {
		let instances = new Array();
		Iif (selector === null) {
			return instances;
		}
 
		const elements = dom.querySelectorAll(selector);
 
		[].forEach.call(elements, element => {
			// Check if plugin has already been instantiated for element
			if (typeof element[this.constructor.name] === 'undefined') { // If no then instantiate it and register it in element
				instances.push(new this(element, {
					selector: selector,
					...options
				}));
			} else { // If Yes then return the existing instance
				instances.push(element[this.constructor.name]);
			}
		});
 
		return instances;
	}
 
	static _interface(options = {}) {
		if (typeof options === 'string') {
			if (typeof this[options] === 'undefined') {
				throw new TypeError(`No method named "${options}"`);
			}
 
			return this[options](options);
		}
 
		return this;
	}
}