Answer the question
In order to leave comments, you need to log in
How to architecturally organize a js project?
Read materials based on presentation by Nicholas Zakas (creator of eslint).
The following extensible architecture for js code is described:
Modules are js+css+html sets of files. A sandbox is essentially a mediator pattern that allows modules to communicate via publish-subscribe and not depend on each other. Kernel - controls module management. Sandboxes refer to it for methods. Base library: jQuery, Django, etc.
I figured out the interaction of sandboxes and modules there:
function Sandbox (core) {
return {
notify: function(data) {
core.getListeners(data.type)
.forEach(item => {
item.notifyCb(data);
});
},
listen: function(eventTypes, notifyCb, moduleInstance) {
eventTypes.forEach(type => {
core.addListener({type, notifyCb, moduleInstance});
});
}
}
}
Core = function(){
var moduleData = {};
var listeners = [];
return {
getListeners: function(type){
return listeners
.filter(item => item.type === type);
},
addListener: function(data){
listeners.push(data);
},
register: function(moduleId, creator){
moduleData[moduleId] = {
creator: creator,
instance: null
}
},
start: function(moduleId){
moduleData[moduleId].instance =
moduleData[moduleId].creator(new Sandbox(this));
moduleData[moduleId].instance.init();
},
stop: function(moduleId){
var data = moduleData[moduleId];
if (data.instance){
data.instance.destroy();
data.instance = null;
}
},
startAll: function(){
for (var moduleId in moduleData){
if (moduleData.hasOwnProperty(moduleId)){
this.start(moduleId);
}
}
},
stopAll: function(){
for (var moduleId in moduleData){
if (moduleData.hasOwnProperty(moduleId)){
this.stop(moduleId);
}
}
}
//другие методы не показаны
}
}();
// Чтобы запустить приложение, следует вначале зарегистрировать требуемые модули и запустить их:
Core.register("module.search", function(sandbox){
return {
init: function(){
//initialization
sandbox.notify({
type: "new-status",
data: '123'
});
}
};
});
// модуль рекламы по результатам запроса
Core.register("module.direct", function(sandbox){
let $container;
return {
init: function(){
//initialization
sandbox.listen(["new-error", "new-status"], this.handleNotification, this);
},
handleNotification: function(note){
switch(note.type){
case "new-error":
// ...
break;
case "new-status":
console.log(note.type, note.data);
break;
}
}
};
});
Core.startAll();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question