edit: This question is about jQuery refactoring. Basically I have a big block of code but I want to see if other folks can think of a better way to refactor it. Since I’m new to jQuery I’m not sure if I’m on the right track or not with my design
original post:
I’m working on a bookmarklet which adds HTML elements to the page. I’m building a sidebar which is a div with a ul inside of it. I’m trying to keep my styles separate from my code and to also write things so that they will be easy to manage if I need to make changes in the future. Is it possible to refactor this code to make it cleaner/more efficient?
myObj = {
$sidebar: {},
createSidebar: function () {
var self = this, $undo = {}, $redo = {}, $email = {}, $reset = {}
self.$sidebar = $("<div id='myObj-sidebar'><ul></ul></div>");
$undo = $('<a></a>', {
id: 'sidebar-undo',
className: 'sidebar-item',
href: '#',
text: 'Undo',
click: function (e) {
//self.doUndo();
e.preventDefault();
}
});
$redo = $('<a></a>', {
id: 'sidebar-redo',
className: 'sidebar-item',
href: '#',
text: 'Redo',
click: function (e) {
//self.doRedo();
e.preventDefault();
}
});
$email = $('<a></a>', {
id: 'sidebar-change-email',
className: 'sidebar-item',
href: '#',
text: 'Change E-Mail',
click: function (e) {
//self.createEmailDialog();
e.preventDefault();
}
});
$reset = $('<a></a>', {
id: 'sidebar-reset-all',
className: 'sidebar-item',
href: '#',
text: 'Reset All',
click: function (e) {
//self.doReset();
e.preventDefault();
}
});
self.$sidebar.find('ul').append($undo, $redo, $email, $reset);
self.$sidebar.find('.sidebar-item').wrap('<li/>');
self.$sidebar.appendTo("body");
}
}
I’m not really sure what the question is – my interpretation is that you’re asking for refactoring advice. If that’s what you’re looking for, here’s the way I’d probably implement the same requirements:
Notes:
e.preventDefault()should generally be the first line of your handler, that way if an exception is thrown later, the anchor will still not navigate (easier to debug);eevent object – to me, this is a more elegant solution than creating aselfreference and a bunch of collection objects (that’s just my opinion).Hope this helps!