装饰器

装饰器

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
/**
* 为dom元素添加事件
* @param {} dom
* @param {*} type
* @param {*} fn
*/
function addEvent(dom, type, fn) {
if (dom.addEventListener) {
dom.addEventListener(type, fn, false)
} else if (dom.attachEvent) {
dom.attachEvent("on" + type, fn)
} else {
dom["on" + type] = fn
}
}

/**
* 装饰已有对象
* @param {*} id
* @param {*} fn
*/
function decorator(id, fn) {
let obj = document.querySelector(id)
if (typeof id.onclick === "function") {
let oldFn = id.onclick
id.onclick = function () {
oldFn()
fn()
}
} else {
obj.onclick = fn
}
}

观察者模式

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
let Observer = (() => {
let _message = {}
return {
regist: function (type, fn) {
if (typeof _message[type] === "undefined") {
_message[type] = [fn]
} else {
_message[type].push(fn)
}
},
fire: function (type, args) {
if (!_message[type]) {
return
}
let events = {
type,
args: args || {},
}
for (let i = 0, len = _message[type].length; i < len; i++) {
_message[type][i].call(this, events)
}
},
remove: function (type, fn) {
if (_message[type] instanceof Array) {
for (let i = _message[type].length - 1; i >= 0; i--) {
_message[type][i] === fn && _message[type].splice(i, 1)
}
}
},
}
})()

Observer.regist("test", function (e) {
// register
console.log(e.type, e.args.msg)
})
Observer.fire("test", { msg: "this is some test message" }) // send