-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathxhpjs.js
105 lines (85 loc) · 2.52 KB
/
xhpjs.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
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function XHPJS(instances, calls) {
this.instanceData = {};
this.instances = {};
this.elements = {};
instances.forEach(function(instance) {
var elementId = instance[0];
this.instanceData[elementId] = instance;
}, this);
calls.forEach(this.call.bind(this));
instances.forEach(function(instance) {
var elementId = instance[0];
this.getInstance(elementId);
}, this);
}
XHPJS.prototype = {
call: function(data) {
var module = data[0];
var method = data[1];
var args = this.mapArguments(data[2]);
module = window[module] ? window[module] : require(module);
method = module[method];
method.apply(null, args);
},
mapArgument: function(arg) {
var type = arg[0];
var data = arg[1];
if (type == 'v') {
return data;
}
if (type == 'e') {
return this.getElement(data);
}
if (type == 'i') {
return this.getInstance(data);
}
},
mapArguments: function(args) {
return args.map(this.mapArgument, this);
},
getElement: function(id) {
if (typeof this.elements[id] == 'undefined') {
this.elements[id] = document.getElementById(id);
}
return this.elements[id];
},
getInstance: function(id) {
if (typeof this.instances[id] == 'undefined') {
this.constructInstance(id);
}
return this.instances[id];
},
constructInstance: function(elementId) {
var data = this.instanceData[elementId];
var moduleName = data[1];
var args = this.mapArguments(data[2]);
var module = window[moduleName] ? window[moduleName] : require(moduleName);
var XHPJSInstance = function(args) {
return module.apply(this, args);
}
XHPJSInstance.prototype = module.prototype;
var instance = new XHPJSInstance(args);
// Handy for debugging :)
instance.__xhpJSModule = moduleName;
instance.__xhpJSElement = this.getElement(elementId);
this.instances[elementId] = instance;
}
}
XHPJS.renderReactElement = function(domElement, module, attributes) {
var React = window.React ? window.React : require('react');
var component = window[module] ? window[module] : require(module);
var reactElement = React.createElement(component, attributes, null);
React.render(reactElement, domElement);
}
if (typeof module != 'undefined' ) {
module.exports = XHPJS;
} else {
window.XHPJS = XHPJS;
}