]> git.lizzy.rs Git - dragonblocks.git/blob - engine/content_mgr.js
Add Map Manager
[dragonblocks.git] / engine / content_mgr.js
1 /*
2  * content_mgr.js
3  *
4  * Copyright 2021 Elias Fleckenstein <eliasfleckenstein@web.de>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  * MA 02110-1301, USA.
20  *
21  *
22  */
23
24 dragonblocks.ContentMgr = class
25 {
26         constructor(baseClass)
27         {
28                 this.baseClass = baseClass;
29                 this.clear();
30         }
31
32         register(name, defClass, override)
33         {
34                 if (! name)
35                         throw new Error("Missing name");
36
37                 if (! name.search(":"))
38                         throw new Error("Non-namespaced name");
39
40                 if (! defClass)
41                         throw new Error("Missing definition class");
42
43                 if (! (defClass.prototype instanceof this.baseClass))
44                         throw new Error("Definition class does not extend base class");
45
46                 let oldDef = this.getDef(name);
47
48                 if (oldDef && ! override)
49                         throw new Error("Already registered");
50
51                 if (! oldDef && override)
52                         throw new Error("Not registered");
53
54                 this.defs[name] = defClass;
55         }
56
57         override(name, def)
58         {
59                 this.register(name, def, true);
60         }
61
62         getDef(name)
63         {
64                 return this.defs[name];
65         }
66
67         create(name, ...args)
68         {
69                 let defClass = this.getDef(name);
70
71                 if (! defClass)
72                         throw new Error("Not defined");
73
74                 return new defClass(...args);
75         }
76
77         clear()
78         {
79                 this.defs = {};
80         }
81 };