Caret/js/command.js

55 lines
1.6 KiB
JavaScript
Raw Normal View History

2013-08-22 06:35:47 +00:00
define(["dom2"], function() {
/*
A module for translating UI interactions into events for the rest of the application. Basically it's a pubsub with a dom layer. Listens for menu events, as well as offering an API for firing and subscribing to arbitrary events.
*/
var commands = {};
var fire = function(command, argument) {
if (!commands[command]) return;
var registry = commands[command].slice();
registry.forEach(function(entry) {
entry.callback.apply(entry.scope || null, argument instanceof Array ? argument : [argument] );
});
2013-08-22 06:35:47 +00:00
}
var register = function(command, listener, scope) {
if (!commands[command]) {
commands[command] = [];
}
commands[command].push({
callback: listener,
scope: scope
});
}
//delegate for all elements that have a command attribute
//may want to add more listeners for other UI elements (select)
document.body.on("click", function(e) {
2013-08-23 23:03:46 +00:00
//cancel on inputs, selectboxes
if (["input", "select"].indexOf(e.target.tagName.toLowerCase()) >= 0) return;
2013-08-22 06:35:47 +00:00
//delegate all items with a command attribute
if (e.target.hasAttribute("command")) {
var command = e.target.getAttribute("command");
var arg = e.target.getAttribute("argument");
fire(command, arg);
}
});
2013-08-23 23:03:46 +00:00
document.body.on("change", function(e) {
if (e.target.hasAttribute("command")) {
var command = e.target.getAttribute("command");
var arg = e.target.value;
fire(command, arg);
}
});
2013-08-22 06:35:47 +00:00
return {
fire: fire,
on: register
};
});