-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
83 lines (59 loc) · 1.81 KB
/
utils.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var Utils = (function ( $ ) {
var Log = function ( domain, enabled ) {
var enabled = enabled || false,
allowedDomain = domain || "/";
if (document.URL.indexOf( allowedDomain ) !== -1 ||
document.URL.indexOf( "localhost" ) !== -1) {
enabled = true;
}
this.print = function ( msg ) {
if (enabled && window.console && window.console.log) {
console.log( msg );
}
}
return this;
};
var CEvent = function (namespace, target) {
this.namespace = namespace ? "." + namespace : "";
this.target = target || $( {} );
this.log = new Log();
};
CEvent.prototype.setTarget = function (target) {
this.target = target;
};
CEvent.prototype.subscribe = function (topic, callback) {
var that = this,
topic = topic + this.namespace;
that.target.on(topic, function (e, params) {
if ( callback && (typeof callback === "function") ) {
callback.apply(callback, [e, params]);
}
});
that.log.print("subscribe -> " + topic);
};
CEvent.prototype.unsubscribe = function (topic) {
var topic = topic + this.namespace;
this.target.off(topic);
this.log.print("unsubscribe -> " + topic);
};
CEvent.prototype.publish = function (topic, params) {
var that = this,
params = params || null,
topic = topic + this.namespace;
that.target.trigger(topic, [params]);
that.log.print("publish -> " + topic);
that.log.print(params);
};
return { Log : Log, CEvent : CEvent };
})( jQuery );
// use
var Event = new Utils.CEvent("somenamespace");
Event.subscribe("sometopic", function (e, params) {
console.log("callback");
console.log(params);
console.log(e.namespace);
console.log(this);
});
Event.publish("sometopic", [{a:1}, "!#", {"ASDASD":123}]);
Event.unsubscribe("sometopic");
Event.publish("sometopic", [{a:1}, "!#", {"ASDASD":123}]);