-
Notifications
You must be signed in to change notification settings - Fork 8
/
event.js
82 lines (71 loc) · 1.85 KB
/
event.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
function EventBus() {
this._events = {};
}
EventBus.prototype.on = function(eventName, callback) {
if (!this._events[eventName]) {
this._events[eventName] = [];
}
this._events[eventName].push(callback);
};
EventBus.prototype.emit = function(eventName, payload) {
if (this._events[eventName]) {
this._events[eventName].forEach(function(callback) {
callback(payload);
});
}
};
function Vue(options) {
this._data = typeof options.data === 'function' ? options.data() : options.data;
this._methods = options.methods;
this._eventBus = new EventBus();
this._proxyData();
this._proxyMethods();
}
Vue.prototype._proxyData = function() {
var self = this;
Object.keys(this._data).forEach(function(key) {
Object.defineProperty(self, key, {
get: function() {
return self._data[key];
},
set: function(newValue) {
self._data[key] = newValue;
}
});
});
};
Vue.prototype._proxyMethods = function() {
var self = this;
var methods = this._methods;
if (methods) {
Object.keys(methods).forEach(function(key) {
self[key] = methods[key].bind(self);
});
}
};
Vue.prototype.$emit = function(eventName, payload) {
this._eventBus.emit(eventName, payload);
};
Vue.prototype.$on = function(eventName, callback) {
this._eventBus.on(eventName, callback);
};
// 使用示例
var app = new Vue({
data: {
message: 'Hello, Vue!'
},
methods: {
greet: function() {
this.$emit('greet', this.message);
},
updateMessage: function(newMessage) {
this.message = newMessage;
}
},
});
app.$on('greet', function(message) {
console.log('Greet:', message);
});
app.greet(); // Output: Greet: Hello, Vue!
app.updateMessage('Hello, World!');
app.greet(); // Output: Greet: Hello, World!