forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.js
More file actions
93 lines (80 loc) · 2.88 KB
/
component.js
File metadata and controls
93 lines (80 loc) · 2.88 KB
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
pc.extend(pc, function () {
/**
* @name pc.Component
* @description Base constructor for a Component
* @class Components are used to attach functionality on a {@link pc.Entity}. Components
* can receive update events each frame, and expose properties to the PlayCanvas Editor.
* @param {pc.ComponentSystem} system The ComponentSystem used to create this Component
* @param {pc.Entity} entity The Entity that this Component is attached to
* @property {Boolean} enabled Enables or disables the component.
*/
var Component = function (system, entity) {
this.system = system;
this.entity = entity;
pc.events.attach(this);
if (this.system.schema && !this._accessorsBuilt) {
this.buildAccessors(this.system.schema);
}
this.on("set", function (name, oldValue, newValue) {
this.fire("set_" + name, name, oldValue, newValue);
});
this.on('set_enabled', this.onSetEnabled, this);
};
Component._buildAccessors = function (obj, schema) {
// Create getter/setter pairs for each property defined in the schema
schema.forEach(function (prop) {
Object.defineProperty(obj, prop, {
get: function () {
return this.data[prop];
},
set: function (value) {
var data = this.data;
var oldValue = data[prop];
data[prop] = value;
this.fire('set', prop, oldValue, value);
},
configurable: true
});
});
obj._accessorsBuilt = true;
};
Component.prototype = {
/**
* @private
* @readonly
* @name pc.Component#data
* @type pc.ComponentData
* @description Access the {@link pc.ComponentData} directly. Usually you should
* access the data properties via the individual properties as modifying this data
* directly will not fire 'set' events.
*/
get data() {
var record = this.system.store[this.entity._guid];
if (record) {
return record.data;
} else {
return null;
}
},
buildAccessors: function (schema) {
Component._buildAccessors(this, schema);
},
onSetEnabled: function (name, oldValue, newValue) {
if (oldValue !== newValue) {
if (this.entity.enabled) {
if (newValue) {
this.onEnable();
} else {
this.onDisable();
}
}
}
},
onEnable: function () { },
onDisable: function () { },
onPostStateChange: function() { }
};
return {
Component: Component
};
}());