I've been using JavaScript for some time now, but mostly just jQuery to prettify web pages. I've started doing some serious development with it in the last year.
So, I want to make sure I'm not doing something stupid. I found a post about the module pattern, and it makes sense to me, so I'm going to attempt to use it on this project instead of keeping nearly everything global.
I'm just a little fuzzy on where I should put event listeners. Is there going to be any issues with scope if the listener is instantiated inside a method? If I'm building something like a toolbar with different functions (kind of like a paint program with 'move', 'select', 'paintbrush', and 'eraser' options), do I keep the onClick for all of those in global scope?
PROJ.namespace("easel");
PROJ.easel.canvas = function() {
//private variable to store current state
var current_mode = "select";
return {
enableSelect: function () {
//disable other tools, enable 'select' event listeners
}
enablePaintbrush: function () {
//disable other tools, enable 'paintbrush' event listeners
}
enableMove: function () {
//disable other tools, enable 'move' event listeners
}
enableEraser: function () {
//disable other tools, enable 'eraser' event listeners
}
};
}();
//event listeners for the tool pallete
$('#tools #paintbrush').on('click', function() { PROJ.easel.canvas.enablePaintbrush() };
$('#tools #move').on('click', function() { PROJ.easel.canvas.enableMove() };
$('#tools #select').on('click', function() { PROJ.easel.canvas.enableSelect() };
$('#tools #eraser').on('click', function() { PROJ.easel.canvas.enableEraser() };
Of course, once the specific tool is selected, it needs its own listeners. For example, a paintbrush needs handlers for 'mousedown' (start painting), 'mousemove' (lay down paint), and 'mouseup' (stop painting). Can those listeners be enabled inside of PROJ.easel.canvas?
EDIT: How are you supposed to pick an "answer" on codereview.stackexchange.com? You're asking peoples' opinions...