patternjavascriptMinor
Context menu with click handlers
Viewed 0 times
clickhandlerswithmenucontext
Problem
I'm trying to learn how to structure my jQuery code better. I'm only about a week into jQuery so if something looks way off please tell me. I'm attempting to use object literals and it appears to work ok, but I am wondering if there is possibly a better way to structure my code.
var application = {
wrapper: $('#wrapper'),
addButton: $('#add'),
init: function() {
this.addButton.click(this.buttonHandlers.clickHandler);
this.wrapper.on("contextmenu", "#wrapper div", this.buttonHandlers.contextMenuHandler);
},
buttonHandlers: {
clickHandler: function(e) {
console.log("clickyHandler");
},
contextMenuHandler: function(e) {
console.log("right click");
return false;
}
}
};
application.init();Solution
This won't scale if you entire application is one large object.
If you seperated it into multiple objects
it will becomes significantly more maintainable.
You may also want to look into techniques for spreading application infrastructure across multiple files. For example ncore uses browserify for it's module system, and uses dependency injection and an expected object format to stitch multiple "modules" together.
If you seperated it into multiple objects
var application = []
application.push({
wrapper: $("#wrapper"),
init: function () {
this.wrapper.on(bla, this.foo)
},
foo: function () {
}
})
...
applications.forEach(function (app) { app.init() })it will becomes significantly more maintainable.
You may also want to look into techniques for spreading application infrastructure across multiple files. For example ncore uses browserify for it's module system, and uses dependency injection and an expected object format to stitch multiple "modules" together.
Code Snippets
var application = []
application.push({
wrapper: $("#wrapper"),
init: function () {
this.wrapper.on(bla, this.foo)
},
foo: function () {
}
})
...
applications.forEach(function (app) { app.init() })Context
StackExchange Code Review Q#10340, answer score: 3
Revisions (0)
No revisions yet.