JavaScript 设计模式: 发布者-订阅者模式
发布者-订阅者模式
https://github.com/Kelichao/javascript.basics/issues/22
https://github.com/Kelichao/javascript.basics/issues/67
http://www.alloyteam.com/2012/10/commonly-javascript-design-pattern-observer-mode/
https://github.com/hustcc/onfire.js
shit codes
观察者模式 ??? 又叫发布者-订阅者模式 ???
https://www.cnblogs.com/xgqfrms/p/12904917.html
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright gildata
*
* @description 观察者模式 ??? 又叫发布者-订阅者模式 ???
* @augments
* @example
*
*/
// 观察者模式
const Events = function () {
let listen,
log,
obj = {},
one,
remove,
trigger,
__this = this;
listen = function (key, eventfn) {
let stack,
_ref; //stack是盒子
_ref = obj[key];
stack = (_ref !== null) ? _ref : obj[key] = [];
return stack.push(eventfn);
};
one = function (key, eventfn) {
remove(key);
return listen(key, eventfn);
};
remove = function (key) {
let _ref;
_ref = obj[key]
return (_ref !== null) ? (_ref.length = 0) : (void 0);
};
trigger = function () {
let fn,
stack,
_i,
_len,
_ref,
key;
key = Array.prototype.shift.call(arguments);
stack = (_ref = obj[key]) !== null
? _ref
: obj[key] = [];
for (_i = 0, _len = stack.length; _i < _len; _i++) {
fn = stack[_i];
if (fn.apply(__this, arguments) === false) {
return false;
}
}
};
return {
listen: listen,
one: one,
remove: remove,
trigger: trigger
};
};
const testBook = Event();
// 订阅者
testBook.listen("play", function (data) {
console.log("今天电影是什么?
${data.name}");
});
// 发布者
testBook.trigger("play", {name: "Javascript设计模式 - 观察者模式"});
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!