-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwatcher3.js
108 lines (95 loc) · 2.59 KB
/
watcher3.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var instance = null;
function EventBus() {
this._events = {};
}
EventBus.prototype.on = function(eventObject, eventName, callback) {
if (!this._events[eventObject]) {
this._events[eventObject] = {};
}
if (!this._events[eventObject][eventName]) {
this._events[eventObject][eventName] = [];
}
this._events[eventObject][eventName].push(callback);
};
EventBus.prototype.emit = function(eventObject, eventName, payload) {
if (this._events[eventObject] && this._events[eventObject][eventName]) {
this._events[eventObject][eventName].forEach(function(callback) {
callback(payload);
});
}
};
function Vue(options) {
instance = this;
this.$options = options;
this._eventBus = new EventBus();
this._data = typeof options.setup === 'function' ? options.setup() : {};
this._proxyData();
}
Vue.prototype._proxyData = function() {
var self = this;
Object.keys(this._data).forEach(function(key) {
Object.defineProperty(self, key, {
get: function() {
var value = self._data[key];
return value?.instance === self ? value.callback() : value;
},
set: function(newValue) {
if (self._data[key]?.instance !== self) {
self._data[key] = newValue;
}
}
});
});
};
function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
if (typeof instance._watchCallback === 'function') {
instance._eventBus.on(target, key, instance._watchCallback);
}
return target[key];
},
set(target, key, value) {
target[key] = value;
instance._eventBus.emit(target, key, value);
}
});
}
function computed(callback) {
return {
instance,
callback
}
}
function watch(source, callback) {
instance._watchCallback = callback;
source();
instance._watchCallback = null;
}
// 使用示例
var app = new Vue({
setup: function() {
const state = reactive({
message: 'Hello, Vue!',
firstName: 'John',
lastName: 'Doe'
});
const fullName = computed(function() {
return state.firstName + ' ' + state.lastName;
});
watch(function() {
return state.message;
}, function(newValue) {
console.log('Message changed:', newValue);
});
return {
state,
fullName
}
}
});
console.log(app.state.message); // Output: Hello, Vue!
app.state.message = 'Hello, Vue.js!'; // Output: Message changed: Hello, Vue.js!
console.log(app.state.message); // Output: Hello, Vue.js!
console.log(app.fullName); // Output: John Doe
app.state.message = 'New message'; // Output: Message changed: New message