UNPKG

35.6 kBJavaScriptView Raw
1/*!
2 * Copyright (c) 2017 NAVER Corp.
3 * @egjs/visible project is licensed under the MIT license
4 *
5 * @egjs/visible JavaScript library
6 * https://naver.github.io/egjs-visible/
7 *
8 * @version 2.2.0
9 *
10 * All-in-one packaged file for ease use of '@egjs/visible' with below dependencies.
11 * NOTE: This is not an official distribution file and is only for user convenience.
12 *
13 */
14(function webpackUniversalModuleDefinition(root, factory) {
15 if(typeof exports === 'object' && typeof module === 'object')
16 module.exports = factory();
17 else if(typeof define === 'function' && define.amd)
18 define([], factory);
19 else if(typeof exports === 'object')
20 exports["Visible"] = factory();
21 else
22 root["eg"] = root["eg"] || {}, root["eg"]["Visible"] = factory();
23})(this, function() {
24return /******/ (function(modules) { // webpackBootstrap
25/******/ // The module cache
26/******/ var installedModules = {};
27/******/
28/******/ // The require function
29/******/ function __webpack_require__(moduleId) {
30/******/
31/******/ // Check if module is in cache
32/******/ if(installedModules[moduleId]) {
33/******/ return installedModules[moduleId].exports;
34/******/ }
35/******/ // Create a new module (and put it into the cache)
36/******/ var module = installedModules[moduleId] = {
37/******/ i: moduleId,
38/******/ l: false,
39/******/ exports: {}
40/******/ };
41/******/
42/******/ // Execute the module function
43/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
44/******/
45/******/ // Flag the module as loaded
46/******/ module.l = true;
47/******/
48/******/ // Return the exports of the module
49/******/ return module.exports;
50/******/ }
51/******/
52/******/
53/******/ // expose the modules object (__webpack_modules__)
54/******/ __webpack_require__.m = modules;
55/******/
56/******/ // expose the module cache
57/******/ __webpack_require__.c = installedModules;
58/******/
59/******/ // define getter function for harmony exports
60/******/ __webpack_require__.d = function(exports, name, getter) {
61/******/ if(!__webpack_require__.o(exports, name)) {
62/******/ Object.defineProperty(exports, name, {
63/******/ configurable: false,
64/******/ enumerable: true,
65/******/ get: getter
66/******/ });
67/******/ }
68/******/ };
69/******/
70/******/ // getDefaultExport function for compatibility with non-harmony modules
71/******/ __webpack_require__.n = function(module) {
72/******/ var getter = module && module.__esModule ?
73/******/ function getDefault() { return module['default']; } :
74/******/ function getModuleExports() { return module; };
75/******/ __webpack_require__.d(getter, 'a', getter);
76/******/ return getter;
77/******/ };
78/******/
79/******/ // Object.prototype.hasOwnProperty.call
80/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
81/******/
82/******/ // __webpack_public_path__
83/******/ __webpack_require__.p = "";
84/******/
85/******/ // Load entry module and return exports
86/******/ return __webpack_require__(__webpack_require__.s = 0);
87/******/ })
88/************************************************************************/
89/******/ ([
90/* 0 */
91/***/ (function(module, exports, __webpack_require__) {
92
93"use strict";
94
95
96var _Visible = __webpack_require__(1);
97
98var _Visible2 = _interopRequireDefault(_Visible);
99
100function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
101
102module.exports = _Visible2["default"]; /**
103 * Copyright (c) NAVER Corp.
104 * egjs-visible projects are licensed under the MIT license
105 */
106
107/***/ }),
108/* 1 */
109/***/ (function(module, exports, __webpack_require__) {
110
111"use strict";
112
113
114exports.__esModule = true;
115
116var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
117
118var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /**
119 * Copyright (c) NAVER Corp.
120 * egjs-visible projects are licensed under the MIT license
121 */
122
123
124var _component = __webpack_require__(2);
125
126var _component2 = _interopRequireDefault(_component);
127
128var _utils = __webpack_require__(3);
129
130function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
131
132function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
133
134function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
135
136function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
137
138// IE8
139// https://stackoverflow.com/questions/43216659/babel-ie8-inherit-issue-with-object-create
140/* eslint-disable */
141if (typeof Object.create !== "function") {
142 Object.create = function (o, properties) {
143 if ((typeof o === "undefined" ? "undefined" : _typeof(o)) !== "object" && typeof o !== "function") {
144 throw new TypeError("Object prototype may only be an Object: " + o);
145 } else if (o === null) {
146 throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
147 }
148 function F() {}
149 F.prototype = o;
150 return new F();
151 };
152}
153var SUPPORT_OBSERVER = !!window.IntersectionObserver;
154var SUPPORT_ELEMENTS_BY_CLASSNAME = function () {
155 var dummy = document.createElement("div");
156
157 if (!dummy.getElementsByClassName) {
158 return false;
159 }
160
161 var dummies = dummy.getElementsByClassName("dummy");
162
163 dummy.innerHTML = "<span class='dummy'></span>";
164 return dummies.length === 1;
165}();
166
167/* eslint-enable */
168
169/**
170 * A Class used to check whether an element is visible in the base element or viewport.
171 * @ko 엘리먼트가 기준 엘리먼트나 뷰포트 안에 보이는지 확인하는 클래스
172 * @alias eg.Visible
173 * @extends eg.Component
174 *
175 * @support {"ie": "8+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
176 */
177
178var Visible = function (_Component) {
179 _inherits(Visible, _Component);
180
181 /**
182 * @param {HTMLElement|String|jQuery} [element=document] A base element that detects if another element is visible<ko>엘리먼트가 보이는 기준 엘리먼트</ko>
183 * @param {Object} options The option object of the Visible module<ko>Visible 모듈의 옵션 객체</ko>
184 * @param {String} [options.targetClass="check_visible"] The class name of the element to be checked<ko>보이는지 확인할 엘리먼트의 클래스 이름</ko>
185 * @param {Number} [options.expandSize=0] The size of the expanded area to be checked whether an element is visible. If this value is less than zero, the size of the area is smaller than that of the base element. <ko>기준 엘리먼트의 경계를 넘어 엘리먼트가 보이는지 확인할 영역의 크기. 값이 0보다 작으면 엘리먼트가 보이는지 확인할 영역의 크기가 기준 엘리먼트보다 작아진다</ko>
186 */
187 function Visible(element, options) {
188 _classCallCheck(this, Visible);
189
190 var _this = _possibleConstructorReturn(this, _Component.call(this));
191
192 _this.options = {
193 targetClass: "check_visible",
194 expandSize: 0
195 };
196 _extends(_this.options, options);
197 _this._wrapper = (0, _utils.$)(element) || document;
198
199 // this._wrapper is Element, or may be Window
200 if (_this._wrapper.nodeType && _this._wrapper.nodeType === 1) {
201 _this._getAreaRect = _this._getWrapperRect;
202 } else {
203 _this._getAreaRect = _utils.getWindowRect;
204 }
205
206 _this._targets = [];
207 _this._timer = null;
208 _this.refresh();
209 return _this;
210 }
211 /**
212 * Updates the list of elements where the visibility property is to be checked
213 * @ko visibility 속성을 검사할 엘리먼트의 목록을 갱신한다
214 * @return {eg.Visible} An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
215 *
216 * @remark
217 * If targets was added or removed from DOM tree, must call refresh method to update internal target list.
218 * <ko>확인 대상이 영역 안에 추가되거나 삭제된 경우, 모듈내부에서 사용하는 확인 대상 목록을 이 메소드를 호출하여 갱신해야한다.<ko>
219 */
220
221
222 Visible.prototype.refresh = function refresh() {
223 if (SUPPORT_ELEMENTS_BY_CLASSNAME) {
224 this._targets = this._wrapper.getElementsByClassName(this.options.targetClass);
225 this.refresh = function () {
226 this._refreshObserver();
227 return this;
228 };
229 } else {
230 this.refresh = function () {
231 var targets = this._wrapper.querySelectorAll("." + this.options.targetClass);
232
233 this._targets = [];
234 for (var i = 0; i < targets.length; i++) {
235 this._targets.push(targets[i]);
236 }
237 this._refreshObserver();
238 return this;
239 };
240 }
241 return this.refresh();
242 };
243
244 /**
245 * Checks whether the visible of the target elements has changed. It trigger that change event on a component.
246 * @ko 대상 엘리먼트의 가시성이 변경됐는지 체크한다. change 이벤트를 발생한다.
247 * @param {Number} [delay=-1] Delay time. It delay that change event trigger.<ko>지연시간. change 이벤트 발생을 지연한다.</ko>
248 * @param {Boolean} [containment=false] Whether to check only elements that are completely contained within the reference area.<ko>기준 영역 안에 완전히 포함된 엘리먼트만 체크할지 여부.</ko>
249 * @return {eg.Visible} An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
250 */
251
252
253 Visible.prototype.check = function check() {
254 var _this2 = this;
255
256 var delay = arguments.length <= 0 ? undefined : arguments[0];
257 var containment = arguments.length <= 1 ? undefined : arguments[1];
258
259 if (typeof delay !== "number") {
260 containment = delay;
261 delay = -1;
262 }
263
264 if (typeof delay === "undefined") {
265 delay = -1;
266 }
267
268 if (typeof containment === "undefined") {
269 containment = false;
270 }
271
272 clearTimeout(this._timer);
273 if (delay < 0) {
274 this._check(containment);
275 this._checkAfter();
276 } else {
277 this._timer = setTimeout(function () {
278 _this2._check(containment);
279 _this2._checkAfter();
280 _this2._timer = null;
281 }, delay);
282 }
283 return this;
284 };
285
286 /**
287 * Get current visible elements.
288 * @ko 현재 보이는 엘리먼트들을 반환한다.
289 * @return {HTMLElement[]} An array of visible elements.<ko>현재 보이는 엘리먼트들의 배열</ko>
290 */
291
292
293 Visible.prototype.getVisibleElements = function getVisibleElements() {
294 var targets = this._targets;
295 var result = [];
296
297 for (var i = 0; i < targets.length; i++) {
298 var el = targets[i];
299
300 if (el && el.__VISIBLE__ === true) {
301 result.push(el);
302 }
303 }
304 return result;
305 };
306
307 Visible.prototype._getWrapperRect = function _getWrapperRect() {
308 return this._wrapper.getBoundingClientRect();
309 };
310
311 Visible.prototype._reviseElements = function _reviseElements() {
312 var _this3 = this;
313
314 if (SUPPORT_ELEMENTS_BY_CLASSNAME) {
315 this._reviseElements = function () {
316 return true;
317 };
318 } else {
319 this._reviseElements = function (target, i) {
320 if (!(0, _utils.hasClass)(target, _this3.options.targetClass)) {
321 target.__VISIBLE__ = null;
322 _this3._targets.splice(i, 1);
323 return false;
324 }
325 return true;
326 };
327 }
328 return this._reviseElements.apply(this, arguments);
329 };
330
331 Visible.prototype._check = function _check(containment) {
332 var expandSize = parseInt(this.options.expandSize, 10);
333
334 var i = void 0;
335 var target = void 0;
336 var targetArea = void 0;
337 var after = void 0;
338
339 // Error Fix: Cannot set property top of #<ClientRect> which has only a getter
340 var rect = this._getAreaRect();
341 var area = {
342 top: rect.top - expandSize,
343 left: rect.left - expandSize,
344 bottom: rect.bottom + expandSize,
345 right: rect.right + expandSize
346 };
347
348 for (i = this._targets.length - 1; target = this._targets[i]; i--) {
349 targetArea = target.getBoundingClientRect();
350
351 if (targetArea.width === 0 && targetArea.height === 0) {
352 continue;
353 }
354
355 if (!this._reviseElements(target, i)) {
356 continue;
357 }
358 if (containment) {
359 after = !(targetArea.top < area.top || targetArea.bottom > area.bottom || targetArea.right > area.right || targetArea.left < area.left);
360 } else {
361 after = !(targetArea.bottom < area.top || area.bottom < targetArea.top || targetArea.right < area.left || area.right < targetArea.left);
362 }
363 target.__AFTER__ = after;
364 }
365 };
366
367 Visible.prototype.checkObserve = function checkObserve() {
368 var _this4 = this;
369
370 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
371
372 if (this._timer) {
373 clearTimeout(this._timer);
374 this._timer = 0;
375 }
376 if (delay < 0) {
377 this._checkAfter();
378 } else {
379 this._timer = setTimeout(function () {
380 _this4._checkAfter();
381 _this4._timer = null;
382 }, delay);
383 }
384 return this;
385 };
386
387 Visible.prototype._checkAfter = function _checkAfter() {
388 var targets = this._targets;
389 var length = targets.length;
390 var visibles = [];
391 var invisibles = [];
392
393 for (var i = 0; i < length; ++i) {
394 var target = targets[i];
395 var prev = target.__VISIBLE__;
396 var after = target.__AFTER__;
397
398 if (prev === after) {
399 continue;
400 }
401 if (after) {
402 visibles.push(target);
403 } else {
404 invisibles.push(target);
405 }
406 target.__VISIBLE__ = after;
407 }
408 if (visibles.length === 0 && invisibles.length === 0) {
409 return;
410 }
411 /**
412 * This event is fired when the event is compared with the last verified one and there is an element of which the visibility property has changed.
413 * @ko 마지막으로 확인한 결과와 비교해 visibility 속성이 변경된 엘리먼트가 있을 때 발생하는 이벤트
414 * @name eg.Visible#change
415 * @event
416 * @type {obejct} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
417 * @property {Array} visible Visible elements (the element type is `HTMLElement`) <ko>보이게 된 엘리먼트들</ko>
418 * @property {Array} invisible Invisible elements (the element type is `HTMLElement`) <ko>안 보이게 된 엘리먼트들</ko>
419 * @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
420 */
421 this.trigger("change", {
422 visible: visibles,
423 invisible: invisibles,
424 isTrusted: true // This event is called by 'check' method.
425 });
426 };
427 /**
428 * Observe whether the visible of the target elements has changed. It trigger that change event on a component.
429 * @ko 대상 엘리먼트의 가시성이 변경됐는지 관찰한다. change 이벤트를 발생한다.
430 * @param {Object} [options={}] Options to observe the target elements. <ko>대상 엘리먼트를 관찰하기 위한 옵션들.</ko>
431 * @param {Number} [options.delay=-1] Delay time. It delay that change event trigger.<ko>지연시간. change 이벤트 발생을 지연한다.</ko>
432 * @param {Boolean} [options.containment=false] Whether to check only elements that are completely contained within the reference area.<ko>기준 영역 안에 완전히 포함된 엘리먼트만 체크할지 여부.</ko>
433 * @return {eg.Visible} An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
434 */
435
436
437 Visible.prototype.observe = function observe() {
438 var _this5 = this;
439
440 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
441
442 if (!SUPPORT_OBSERVER) {
443 this._addObserveEvent(options);
444 return this;
445 }
446 var delay = typeof options.delay === "undefined" ? -1 : options.delay;
447 var containment = !!options.containment;
448
449 this._observeCallback = function (entries) {
450 entries.forEach(function (entry) {
451 entry.target.__AFTER__ = containment ? entry.intersectionRatio >= 1 : entry.isIntersecting;
452 });
453 _this5._checkAfter(delay);
454 };
455 if (this._observer) {
456 this.unobserve();
457 }
458 this._observer = new IntersectionObserver(this._observeCallback, {
459 root: this._wrapper.nodeType === 1 ? this._wrapper : null,
460 rootMargin: this.options.expandSize + "px",
461 threshold: containment ? [0, 1] : [0]
462 });
463 var observer = this._observer;
464 var targets = this._targets;
465 var length = targets.length;
466
467 for (var i = 0; i < length; ++i) {
468 observer.observe(targets[i]);
469 }
470 return this;
471 };
472
473 Visible.prototype.unobserve = function unobserve() {
474 if (!this._observeCallback) {
475 return this;
476 }
477 if (SUPPORT_OBSERVER) {
478 this._observer && this._observer.disconnect();
479 } else {
480 (0, _utils.removeEvent)(this._wrapper, "scroll", this._observeCallback);
481 (0, _utils.removeEvent)(this._wrapper, "resize", this._observeCallback);
482 }
483 this._observer = null;
484 this._observeCallback = null;
485 return this;
486 };
487
488 Visible.prototype._refreshObserver = function _refreshObserver() {
489 if (!this._observer) {
490 return;
491 }
492 this._observer.disconnect();
493 var targets = this._targets;
494 var length = targets.length;
495
496 for (var i = 0; i < length; ++i) {
497 this._observer.observe(targets[i]);
498 }
499 };
500
501 Visible.prototype._addObserveEvent = function _addObserveEvent() {
502 var _this6 = this;
503
504 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
505
506 if (this._observeCallback) {
507 return;
508 }
509 var delay = typeof options.delay === "undefined" ? -1 : options.delay;
510 var containment = !!options.containment;
511
512 this._observeCallback = function (e) {
513 _this6._check(containment);
514 _this6.checkObserve(delay);
515 };
516 (0, _utils.addEvent)(this._wrapper, "scroll", this._observeCallback);
517 (0, _utils.addEvent)(this._wrapper, "resize", this._observeCallback);
518
519 this._observeCallback();
520 };
521
522 Visible.prototype.destroy = function destroy() {
523 this.off();
524 this.unobserve();
525 this._targets = [];
526 this._wrapper = null;
527 this._timer = null;
528 };
529
530 return Visible;
531}(_component2["default"]);
532
533Visible.VERSION = "2.2.0";
534exports["default"] = Visible;
535module.exports = exports["default"];
536
537/***/ }),
538/* 2 */
539/***/ (function(module, exports, __webpack_require__) {
540
541/*!
542 * Copyright (c) 2017 NAVER Corp.
543 * @egjs/component project is licensed under the MIT license
544 *
545 * @egjs/component JavaScript library
546 * http://naver.github.io/egjs/component
547 *
548 * @version 2.1.0
549 */
550(function webpackUniversalModuleDefinition(root, factory) {
551 if(true)
552 module.exports = factory();
553 else if(typeof define === 'function' && define.amd)
554 define([], factory);
555 else if(typeof exports === 'object')
556 exports["Component"] = factory();
557 else
558 root["eg"] = root["eg"] || {}, root["eg"]["Component"] = factory();
559})(this, function() {
560return /******/ (function(modules) { // webpackBootstrap
561/******/ // The module cache
562/******/ var installedModules = {};
563/******/
564/******/ // The require function
565/******/ function __webpack_require__(moduleId) {
566/******/
567/******/ // Check if module is in cache
568/******/ if(installedModules[moduleId]) {
569/******/ return installedModules[moduleId].exports;
570/******/ }
571/******/ // Create a new module (and put it into the cache)
572/******/ var module = installedModules[moduleId] = {
573/******/ i: moduleId,
574/******/ l: false,
575/******/ exports: {}
576/******/ };
577/******/
578/******/ // Execute the module function
579/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
580/******/
581/******/ // Flag the module as loaded
582/******/ module.l = true;
583/******/
584/******/ // Return the exports of the module
585/******/ return module.exports;
586/******/ }
587/******/
588/******/
589/******/ // expose the modules object (__webpack_modules__)
590/******/ __webpack_require__.m = modules;
591/******/
592/******/ // expose the module cache
593/******/ __webpack_require__.c = installedModules;
594/******/
595/******/ // define getter function for harmony exports
596/******/ __webpack_require__.d = function(exports, name, getter) {
597/******/ if(!__webpack_require__.o(exports, name)) {
598/******/ Object.defineProperty(exports, name, {
599/******/ configurable: false,
600/******/ enumerable: true,
601/******/ get: getter
602/******/ });
603/******/ }
604/******/ };
605/******/
606/******/ // getDefaultExport function for compatibility with non-harmony modules
607/******/ __webpack_require__.n = function(module) {
608/******/ var getter = module && module.__esModule ?
609/******/ function getDefault() { return module['default']; } :
610/******/ function getModuleExports() { return module; };
611/******/ __webpack_require__.d(getter, 'a', getter);
612/******/ return getter;
613/******/ };
614/******/
615/******/ // Object.prototype.hasOwnProperty.call
616/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
617/******/
618/******/ // __webpack_public_path__
619/******/ __webpack_require__.p = "";
620/******/
621/******/ // Load entry module and return exports
622/******/ return __webpack_require__(__webpack_require__.s = 0);
623/******/ })
624/************************************************************************/
625/******/ ([
626/* 0 */
627/***/ (function(module, exports, __webpack_require__) {
628
629"use strict";
630
631
632var _Component = __webpack_require__(1);
633
634var _Component2 = _interopRequireDefault(_Component);
635
636function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
637
638_Component2["default"].VERSION = "2.1.0";
639module.exports = _Component2["default"];
640
641/***/ }),
642/* 1 */
643/***/ (function(module, exports, __webpack_require__) {
644
645"use strict";
646
647
648exports.__esModule = true;
649
650var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
651
652function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
653
654/**
655 * Copyright (c) 2015 NAVER Corp.
656 * egjs projects are licensed under the MIT license
657 */
658
659/**
660 * A class used to manage events and options in a component
661 * @ko 컴포넌트의 이벤트와 옵션을 관리할 수 있게 하는 클래스
662 * @alias eg.Component
663 */
664var Component = function () {
665 /**
666 * @support {"ie": "7+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
667 */
668 function Component() {
669 _classCallCheck(this, Component);
670
671 this._eventHandler = {};
672 this.options = {};
673 }
674 /**
675 * Triggers a custom event.
676 * @ko 커스텀 이벤트를 발생시킨다
677 * @param {String} eventName The name of the custom event to be triggered <ko>발생할 커스텀 이벤트의 이름</ko>
678 * @param {Object} customEvent Event data to be sent when triggering a custom event <ko>커스텀 이벤트가 발생할 때 전달할 데이터</ko>
679 * @return {Boolean} Indicates whether the event has occurred. If the stop() method is called by a custom event handler, it will return false and prevent the event from occurring. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">Ref</a> <ko>이벤트 발생 여부. 커스텀 이벤트 핸들러에서 stop() 메서드를 호출하면 'false'를 반환하고 이벤트 발생을 중단한다. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">참고</a></ko>
680 * @example
681 class Some extends eg.Component {
682 some(){
683 if(this.trigger("beforeHi")){ // When event call to stop return false.
684 this.trigger("hi");// fire hi event.
685 }
686 }
687 }
688 const some = new Some();
689 some.on("beforeHi", (e) => {
690 if(condition){
691 e.stop(); // When event call to stop, `hi` event not call.
692 }
693 });
694 some.on("hi", (e) => {
695 // `currentTarget` is component instance.
696 console.log(some === e.currentTarget); // true
697 });
698 // If you want to more know event design. You can see article.
699 // https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F
700 */
701
702
703 Component.prototype.trigger = function trigger(eventName) {
704 var customEvent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
705
706 var handlerList = this._eventHandler[eventName] || [];
707 var hasHandlerList = handlerList.length > 0;
708
709 if (!hasHandlerList) {
710 return true;
711 }
712
713 // If detach method call in handler in first time then handeler list calls.
714 handlerList = handlerList.concat();
715
716 customEvent.eventType = eventName;
717
718 var isCanceled = false;
719 var arg = [customEvent];
720 var i = 0;
721
722 customEvent.stop = function () {
723 isCanceled = true;
724 };
725 customEvent.currentTarget = this;
726
727 for (var _len = arguments.length, restParam = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
728 restParam[_key - 2] = arguments[_key];
729 }
730
731 if (restParam.length >= 1) {
732 arg = arg.concat(restParam);
733 }
734
735 for (i = 0; handlerList[i]; i++) {
736 handlerList[i].apply(this, arg);
737 }
738
739 return !isCanceled;
740 };
741 /**
742 * Executed event just one time.
743 * @ko 이벤트가 한번만 실행된다.
744 * @param {eventName} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
745 * @param {Function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
746 * @return {eg.Component} An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
747 * @example
748 class Some extends eg.Component {
749 hi() {
750 alert("hi");
751 }
752 thing() {
753 this.once("hi", this.hi);
754 }
755 }
756 var some = new Some();
757 some.thing();
758 some.trigger("hi");
759 // fire alert("hi");
760 some.trigger("hi");
761 // Nothing happens
762 */
763
764
765 Component.prototype.once = function once(eventName, handlerToAttach) {
766 if ((typeof eventName === "undefined" ? "undefined" : _typeof(eventName)) === "object" && typeof handlerToAttach === "undefined") {
767 var eventHash = eventName;
768 var i = void 0;
769
770 for (i in eventHash) {
771 this.once(i, eventHash[i]);
772 }
773 return this;
774 } else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
775 var self = this;
776
777 this.on(eventName, function listener() {
778 for (var _len2 = arguments.length, arg = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
779 arg[_key2] = arguments[_key2];
780 }
781
782 handlerToAttach.apply(self, arg);
783 self.off(eventName, listener);
784 });
785 }
786
787 return this;
788 };
789
790 /**
791 * Checks whether an event has been attached to a component.
792 * @ko 컴포넌트에 이벤트가 등록됐는지 확인한다.
793 * @param {String} eventName The name of the event to be attached <ko>등록 여부를 확인할 이벤트의 이름</ko>
794 * @return {Boolean} Indicates whether the event is attached. <ko>이벤트 등록 여부</ko>
795 * @example
796 class Some extends eg.Component {
797 some() {
798 this.hasOn("hi");// check hi event.
799 }
800 }
801 */
802
803
804 Component.prototype.hasOn = function hasOn(eventName) {
805 return !!this._eventHandler[eventName];
806 };
807
808 /**
809 * Attaches an event to a component.
810 * @ko 컴포넌트에 이벤트를 등록한다.
811 * @param {eventName} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
812 * @param {Function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
813 * @return {eg.Component} An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
814 * @example
815 class Some extends eg.Component {
816 hi() {
817 console.log("hi");
818 }
819 some() {
820 this.on("hi",this.hi); //attach event
821 }
822 }
823 */
824
825
826 Component.prototype.on = function on(eventName, handlerToAttach) {
827 if ((typeof eventName === "undefined" ? "undefined" : _typeof(eventName)) === "object" && typeof handlerToAttach === "undefined") {
828 var eventHash = eventName;
829 var name = void 0;
830
831 for (name in eventHash) {
832 this.on(name, eventHash[name]);
833 }
834 return this;
835 } else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
836 var handlerList = this._eventHandler[eventName];
837
838 if (typeof handlerList === "undefined") {
839 this._eventHandler[eventName] = [];
840 handlerList = this._eventHandler[eventName];
841 }
842
843 handlerList.push(handlerToAttach);
844 }
845
846 return this;
847 };
848 /**
849 * Detaches an event from the component.
850 * @ko 컴포넌트에 등록된 이벤트를 해제한다
851 * @param {eventName} eventName The name of the event to be detached <ko>해제할 이벤트의 이름</ko>
852 * @param {Function} handlerToDetach The handler function of the event to be detached <ko>해제할 이벤트의 핸들러 함수</ko>
853 * @return {eg.Component} An instance of a component itself <ko>컴포넌트 자신의 인스턴스</ko>
854 * @example
855 class Some extends eg.Component {
856 hi() {
857 console.log("hi");
858 }
859 some() {
860 this.off("hi",this.hi); //detach event
861 }
862 }
863 */
864
865
866 Component.prototype.off = function off(eventName, handlerToDetach) {
867 // All event detach.
868 if (typeof eventName === "undefined") {
869 this._eventHandler = {};
870 return this;
871 }
872
873 // All handler of specific event detach.
874 if (typeof handlerToDetach === "undefined") {
875 if (typeof eventName === "string") {
876 this._eventHandler[eventName] = undefined;
877 return this;
878 } else {
879 var eventHash = eventName;
880 var name = void 0;
881
882 for (name in eventHash) {
883 this.off(name, eventHash[name]);
884 }
885 return this;
886 }
887 }
888
889 // The handler of specific event detach.
890 var handlerList = this._eventHandler[eventName];
891
892 if (handlerList) {
893 var k = void 0;
894 var handlerFunction = void 0;
895
896 for (k = 0; (handlerFunction = handlerList[k]) !== undefined; k++) {
897 if (handlerFunction === handlerToDetach) {
898 handlerList = handlerList.splice(k, 1);
899 break;
900 }
901 }
902 }
903
904 return this;
905 };
906
907 return Component;
908}();
909
910exports["default"] = Component;
911module.exports = exports["default"];
912
913/***/ })
914/******/ ]);
915});
916//# sourceMappingURL=component.js.map
917
918/***/ }),
919/* 3 */
920/***/ (function(module, exports, __webpack_require__) {
921
922"use strict";
923
924
925exports.__esModule = true;
926
927var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
928
929exports.toArray = toArray;
930exports.$ = $;
931exports.getWindowRect = getWindowRect;
932exports.hasClass = hasClass;
933exports.addEvent = addEvent;
934exports.removeEvent = removeEvent;
935
936var SUPPORT_ADDEVENTLISTENER = !!("addEventListener" in document);
937var SUPPORT_PASSIVE = function () {
938 var supportsPassiveOption = false;
939
940 try {
941 if (SUPPORT_ADDEVENTLISTENER && Object.defineProperty) {
942 document.addEventListener("test", null, Object.defineProperty({}, "passive", {
943 get: function get() {
944 supportsPassiveOption = true;
945 }
946 }));
947 }
948 } catch (e) {}
949 return supportsPassiveOption;
950}();
951
952function toArray(nodes) {
953 // SCRIPT5014 in IE8
954 var array = [];
955
956 if (nodes) {
957 for (var i = 0, len = nodes.length; i < len; i++) {
958 array.push(nodes[i]);
959 }
960 }
961 return array;
962}
963
964/**
965 * Select or create element
966 * @param {String|HTMLElement|jQuery} param
967 * when string given is as HTML tag, then create element
968 * otherwise it returns selected elements
969 * @param {Boolean} multi
970 * @returns {HTMLElement|HTMLElement[]|undefined}
971 */
972function $(param) {
973 var multi = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
974
975 var el = void 0;
976
977 if (param === undefined) {
978 return undefined;
979 }
980
981 if (typeof param === "string") {
982 // String (HTML, Selector)
983 // check if string is HTML tag format
984 var match = param.match(/^<([a-z]+)\s*([^>]*)>/);
985
986 // creating element
987 if (match) {
988 // HTML
989 var dummy = document.createElement("div");
990
991 dummy.innerHTML = param;
992 el = toArray(dummy.childNodes);
993 } else {
994 // Selector
995 el = toArray(document.querySelectorAll(param));
996 }
997 if (!multi) {
998 el = el.length >= 1 ? el[0] : undefined;
999 }
1000 } else if (param === window) {
1001 // window
1002 el = param;
1003 } else if (param.nodeName && (param.nodeType === 1 || param.nodeType === 9)) {
1004 // HTMLElement, Document
1005 el = param;
1006 } else if ("jQuery" in window && param instanceof jQuery || param.constructor.prototype.jquery) {
1007 // jQuery
1008 el = multi ? param.toArray() : param.get(0);
1009 } else if (Array.isArray(param)) {
1010 el = param.map(function (v) {
1011 return $(v);
1012 });
1013 if (!multi) {
1014 el = el.length >= 1 ? el[0] : undefined;
1015 }
1016 }
1017 return el;
1018}
1019function getWindowRect() {
1020 // [IE7] document.documentElement.clientHeight has always value 0 (bug)
1021 return {
1022 top: 0,
1023 left: 0,
1024 bottom: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
1025 right: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
1026 };
1027}
1028function hasClass(el, className) {
1029 if (el.classList) {
1030 return el.classList.contains(className);
1031 } else {
1032 return new RegExp("(^| )" + className + "( |$)", "gi").test(el.className);
1033 }
1034}
1035function addEvent(element, type, handler, eventListenerOptions) {
1036 if (SUPPORT_ADDEVENTLISTENER) {
1037 var options = eventListenerOptions || false;
1038
1039 if ((typeof eventListenerOptions === "undefined" ? "undefined" : _typeof(eventListenerOptions)) === "object") {
1040 options = SUPPORT_PASSIVE ? eventListenerOptions : false;
1041 }
1042 element.addEventListener(type, handler, options);
1043 } else if (element.attachEvent) {
1044 element.attachEvent("on" + type, handler);
1045 } else {
1046 element["on" + type] = handler;
1047 }
1048}
1049function removeEvent(element, type, handler) {
1050 if (element.removeEventListener) {
1051 element.removeEventListener(type, handler, false);
1052 } else if (element.detachEvent) {
1053 element.detachEvent("on" + type, handler);
1054 } else {
1055 element["on" + type] = null;
1056 }
1057}
1058
1059/***/ })
1060/******/ ]);
1061});
\No newline at end of file