Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// пример модуля
Core.register('module-name', function(sandbox) {
return {
init: function() {
// constrictor
if (sandbox.testSomething()) {
console.log('yes, you can!');
}
},
destroy: function() {
// destructor
}
};
});
// ядро
Core = (function () {
var modules = {},
debug = false;
function createInstance(moduleId){
var instance = modules[moduleId].creator(new Sandbox(this)),
name,
method;
if (!debug) {
for (name in instance) {
method = instance[name];
if (typeof method === 'function') {
instance[name] = (function(name, method) {
return function() {
try {
return method.apply(this, arguments);
} catch(ex) {
log(1, name + "(): " + ex.message);
}
};
})(name, method);
}
}
}
return instance;
};
return {
register: function(moduleId, creator) {
modules[moduleId] = {
creator: creator,
instance: null
};
},
start: function(moduleId) {
modules[moduleId].instance = modules[moduleId].creator(new Sandbox(this));
modules[moduleId].instance.init();
},
stop: function(moduleId) {
var module = modules[moduleId];
if (module.instance) {
module.instance.destroy;
module.instance = null;
}
},
startAll: function() {
for (var moduleId in modules) {
if (modules.hasOwnProperty(moduleId)) {
this.start(moduleId);
}
}
},
stopAll: function() {
for (var moduleId in modules) {
if (modules.hasOwnProperty(moduleId)) {
this.stop(moduleId);
}
}
}
};
})();
// start app
Core.stopAll();
// пример взаимодействия модулей через события
Core.register('timeline-filter', function(sandbox) {
return {
changeFilter: function(filter) {
sandbox.notify({
type: 'timeline-filter-change',
data: filter
});
}
};
});
Core.register('status-poster', function(sandbox) {
return {
postStatus: function(statusText) {
sandbox.notify({
type: 'post-status',
data: statusText
});
}
};
});
Core.register('timeline', function(sandbox) {
return {
init: function() {
sandbox.listen([
'timeline-filter-change',
'post-status'
], this.handleNotification, this);
},
handleNotification: function(note) {
switch(note.type) {
case 'timeline-filter-change':
this.applyFilter(note.data);
return;
case 'post-status':
this.post(note.data);
return;
}
}
};
});
//
var id = sandbox.request({ name: "value" }, {
success: function(response) {
handleSuccess(response.data);
},
failure: function(response) {
handleFailure();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.