Skip to content

Instantly share code, notes, and snippets.

@patrick99e99
Created January 23, 2011 04:16
Show Gist options
  • Save patrick99e99/791812 to your computer and use it in GitHub Desktop.
Save patrick99e99/791812 to your computer and use it in GitHub Desktop.
var Core = (function($) {
return {
modules: {},
addModule: function(module_name, fn) {
// create new sandbox for module
var sandbox = new Sandbox(module_name);
// store the module
var module = this.modules[module_name] = { constructor: fn, sandbox: sandbox, instance: null, listening_list: {} };
module.instance = module.constructor(sandbox).init();
},
addToListeningList: function(name, fn, module_name) {
var module = this.modules[module_name];
if (module) {
module.listening_list[name] = fn;
}
},
fireEvent: function(name, data) {
for (var mod_name in this.modules) {
var list = this.modules[mod_name].listening_list;
if (list[name] && this.isFunction(list[name])) {
list[name](data);
delete list[name];
}
}
},
// library specific methods:
bind: function(element, evt, fn) {
$(element).bind(evt, fn);
},
isFunction: function(obj) {
return $.isFunction(obj);
},
find: function(selector) {
return $(selector);
}
};
})(jQuery);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Scalable js test</title>
<link rel="stylesheet" href="main.css" />
</head>
<body>
<h1 id="foo">scalable js test</h1>
<h2 id="bar">does this really work???</h2>
</body>
<script src="js/jquery-1.4.2.min.js"></script>
<script src="js/core-jquery.js"></script>
<script src="js/sandbox.js"></script>
<script src="js/modules.js"></script>
</html>
Core.addModule('module1', function(sandbox) {
return {
init: function() {
var h1 = Core.find('#foo');
Core.bind(h1, 'click', this.bar);
},
bar: function() {
alert('clicked!');
sandbox.notify('omg', 'lol!!!');
}
}
});
Core.addModule('module2', function(sandbox) {
return {
init: function() {
sandbox.listen('omg', function(foo) {
alert('This is a resonse with some data passed in: ' + foo);
});
}
}
});
var Sandbox = function(module_name) {
// connect the sandbox instance to it's module
this.module_name = module_name;
// interface with the core
this.find = function(selector) {
return Core.find(selector);
};
this.listen = function(name, fn) {
Core.addToListeningList(name, fn, module_name);
};
this.notify = function(name, data) {
Core.fireEvents(name, data);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment