-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmozart.js
76 lines (72 loc) · 3.19 KB
/
mozart.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
class Component {
constructor(name) {
let native_methods = {
name: undefined,
store: {},
assign(obj) {
// Rejiggering native methods so they work with Object.defineProperty
let _native_methods = {}
for (let key in native_methods) {
let val = native_methods[key];
_native_methods[key] = { value: val, writable: true }
}
Object.defineProperties(obj, _native_methods);
for (let key in obj) {
let prop_descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (!!prop_descriptor['get']) {
Object.defineProperty(ThisProxyComponent, key, { get() {
return obj[key]
} });
}
else if (!!prop_descriptor['set']) {
Object.defineProperty(ThisProxyComponent, key, { set(...args) {
return obj[key] = args[0]
} });
}
else if (!!prop_descriptor.value && typeof(prop_descriptor.value) === "function") {
ThisProxyComponent[key] = (...args) => obj[key].apply(obj, args);
}
else {
// Assuming at this point it's a non-computed value.
ThisProxyComponent[key] = obj[key];
}
}
},
q(el) {
let scoped_query = `[data-component~="${this.name}"]`;
if (el) scoped_query += ` ${el}`;
const elements = document.querySelectorAll(scoped_query);
return elements.length > 1 ? Array.from(elements) : elements[0];
},
get me() { return this.q(); },
register(name) { this.name = name; },
}
let ThisProxyComponent = new Proxy(native_methods,
{
set(obj, prop, value) {
if (obj.hasOwnProperty(prop)) {
return obj[prop] = value;
}
else if (typeof(value) === "function") {
let _native_methods = {}
for (let key in native_methods) {
let val = native_methods[key];
_native_methods[key] = { value: val, writable: true }
}
let _value = Object.defineProperties(value, _native_methods);
Object.defineProperty(obj, prop, { value: _value.bind(ThisProxyComponent), writable: true });
return true;
}
else {
console.error(`Value ${value} was not a function on ${ThisProxyComponent.name} component. Type of ${value} is ${typeof(value)}`);
throw `${ThisProxyComponent.name}: Value was not a function. Use .store on the component to store new information`;
}
},
get(obj, prop) { return obj[prop]; }
}
);
ThisProxyComponent.register(name);
return ThisProxyComponent;
}
}
export default Component;