UNPKG

strudel

Version:

A front-end framework for back-end powered web.

104 lines (88 loc) 2.23 kB
import EventEmitter from '../util/eventEmitter'; import { isFunction } from '../util/helpers'; import mix from './mixin'; import config from '../config'; import handleError from '../util/error'; /** * @classdesc Base class for all components, implementing event emitter * @class * @hideconstructor */ class Component extends EventEmitter { constructor({ element, data } = {}) { super(); this.mixins = this.mixins || []; try { this.mixins.forEach((mixin) => { if (isFunction(mixin.beforeInit)) { mixin.beforeInit.call(this); } mix(this, mixin); }); this.beforeInit(); this.$element = element; this.$data = data; if (this.__decorators__) { this.__decorators__.forEach((fn) => { fn(this); }); delete this.__decorators__; } this.mixins.forEach((mixin) => { if (isFunction(mixin.init)) { mixin.init.call(this); } }); this.init(); } catch (e) { handleError(e, this.constructor, 'component hook'); } this.$element.addClass(config.initializedClassName); } /** * Function called before component is initialized * @interface */ beforeInit() {} /** * Function called when component is initialized * @interface */ init() {} /** * Function called before component is destroyed * @interface */ beforeDestroy() {} /** * Function called after component is destroyed * @interface */ destroy() {} /** * Teardown the component and clear events */ $teardown() { try { this.mixins.forEach((mixin) => { if (isFunction(mixin.beforeDestroy)) { mixin.beforeDestroy.call(this); } }); this.beforeDestroy(); this.$element.off(); this.$element.removeClass(config.initializedClassName); delete this.$element.first().__strudel__; delete this.$element; this.mixins.forEach((mixin) => { if (isFunction(mixin.destroy)) { mixin.destroy.call(this); } }); this.destroy(); } catch (e) { handleError(e, this.constructor, 'component hook'); } } } export default Component;