@yugu/subscribe
Version:
使用`import Subscribe from "@yugu/subscribe"`导入类 通过`const pool = new Subscribe`创建发布订阅实例 该类实例可以通过`add`方式向订阅池中添加事件,`pool.add(fn)` 该类实例可以通过`remove`方式从订阅池中移除事件,`pool.remove(fn)` 该类实例可以通过`fire`方式触发订阅池中所有的函数,`pool.fire()` ```js <script type="module"> imp
49 lines (46 loc) • 1.11 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true});// src/index.js
var isFn = (fn) => {
return typeof fn === "function" && typeof fn.nodeType !== "number";
};
var Subscribe = class {
constructor() {
this.callbacks = [];
}
/**
* 添加方法,判断是否是函数,并且需要做去重的校验
* @param {*} fn
*/
add(fn) {
if (isFn(fn)) {
const isExist = this.callbacks.some((cb) => fn === cb);
!isExist ? this.callbacks.push(fn) : null;
}
}
/**
* 移除方法
* @param {*} fn
*/
remove(fn) {
const index = this.callbacks.indexOf(fn);
if (index !== -1) {
this.callbacks.splice(index, 1, null);
}
}
/**
* 触发方法并支持传值
* @param {...any} args
*/
fire(...args) {
for (let index = 0; index < this.callbacks.length; index++) {
const cb = this.callbacks[index];
if (!isFn(cb)) {
this.callbacks.splice(index, 1);
index--;
continue;
}
cb.call(this, ...args);
}
}
};
var src_default = Subscribe;
exports.default = src_default;