UNPKG

2.35 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Base');
7
8module.exports = class BehaviorManager extends Base {
9
10 get (name) {
11 this.ensure();
12 return this._behaviorMap[name] instanceof Behavior ? this._behaviorMap[name] : null;
13 }
14
15 attach (name, data) {
16 this.ensure();
17 return this.attachInternal(name, data);
18 }
19
20 attachOnce (name, data) {
21 return this.get(name) || this.attachInternal(name, data);
22 }
23
24 detach (name) {
25 const behavior = this.get(name);
26 if (behavior) {
27 delete this._behaviorMap[name];
28 behavior.detach();
29 }
30 return behavior;
31 }
32
33 getAll () {
34 this.ensure();
35 return this._behaviorMap;
36 }
37
38 attachAll (data) {
39 this.ensure();
40 for (const name of Object.keys(data)) {
41 this.attachInternal(name, data[name]);
42 }
43 }
44
45 detachAll () {
46 this.ensure();
47 for (const name of Object.keys(this._behaviorMap)) {
48 this.detach(name);
49 }
50 }
51
52 ensure () {
53 if (this._behaviorMap) {
54 return;
55 }
56 this._behaviorMap = {};
57 if (this.autoAttachedMap) {
58 for (const name of Object.keys(this.autoAttachedMap)) {
59 this.attach(name, this.autoAttachedMap[name]);
60 }
61 }
62 }
63
64 attachInternal (name, behavior) {
65 if (!behavior) {
66 throw new Error(`Attach undefined behavior: ${name}`);
67 }
68 if (behavior.prototype instanceof Behavior) {
69 behavior = new behavior({name});
70 } else if (behavior.Class && behavior.Class.prototype instanceof Behavior) {
71 behavior.name = behavior.name || name;
72 behavior = new behavior.Class(behavior);
73 } else if (!(behavior instanceof Behavior)) {
74 throw new Error(`Attach invalid behavior: ${name}`);
75 }
76 if (this._behaviorMap[name] instanceof Behavior) {
77 this._behaviorMap[name].detach();
78 }
79 behavior.attach(this.owner);
80 this._behaviorMap[name] = behavior;
81 return behavior;
82 }
83};
84
85const Behavior = require('./Behavior');
\No newline at end of file