- I am working on a Python/Django project which has turned into a JavaScript/jQuery project due to the amount of asynchronous functionality that I thought to add.
- There is a JavaScript file which is doing everything for the JS side. I am a newbie in JavaScript/jQuery and am starting to think that this is going to become a big problem soon.
- I asked for a previous review but as I never got one there and the file has changed a lot since then I am placing part of the file where I think something can be be improved.
Some functions which are being used by the code:
function bind_events(cur_obj, e) {
var trigger_name = "";
if (e.keyCode == 13) {
trigger_name = EV_ENTER_KEY;
} else if (e.altKey && e.keyCode == "N".charCodeAt(0)) {
trigger_name = EV_ALT_N;
}
$(cur_obj).trigger(trigger_name);
}
//Auxiliary functions for categories
function get_all_categories() {
var class_ids = [];
$(CLASS_DEL_CATEGORY).each(function () {
class_ids.push(get_class_string(this, 11));
});
return class_ids.join(",");
}
function enter_category(category_box, trigger_event, trigger_data) {
if (value_in_selector(category_box, CLASS_UI_MENU_ITEM) == false) {
alert(MSG_NOT_CATEGORY);
} else if (value_in_selector(category_box, CLASS_CATEGORY) == true) {
alert(MSG_CATEGORY_ADDED);
category_box.val("");
} else {
category_box.trigger(trigger_event, trigger_data);
}
}
function add_category(cur_obj, e, data) {
$.ajax({
url: URL_CATEGORY,
data: {'value': $(cur_obj).val()},
success: function (output) {
data.cat_list.append(output);
$(cur_obj).val("");
if (data.trigger_obj !== undefined) {
data.trigger_obj.trigger(data.next_trig);
}
}
});
}
The code that I think needs to be improved is below.
//Actions for Search's category box
CATEGORY_INPUT.on({
keyup: function (e) {
bind_events(this, e);
},
"enterKey": function () {
enter_category($(this), EV_ADD_CATEGORY, [
{
cat_list: CATEGORY_LIST_SEARCH,
trigger_obj: BOOKMARK_LIST,
next_trig: EV_UPDATE_BOOKMARKS
}
])
},
"addCategory": function (e, data) {
add_category(this, e, data);
},
"clearAll": function () {
$(CLASS_CATEGORY).remove();
$(this).val("");
BOOKMARK_LIST.trigger(EV_CLEAR_ALL);
}
});
//Actions for Add Bookmark's category box
CATEGORY_BOX.on({
keyup: function (e) {
bind_events(this, e);
},
"enterKey": function () {
enter_category($(this), EV_ADD_CATEGORY, [
{
cat_list: CATEGORY_LIST_ADD,
trigger_obj: undefined,
next_trig: undefined
}
])
},
"addCategory": function (e, data) {
add_category(this, e, data);
}
});
As you can see nearly same events are bound to both with minor changes. I thought to bind events to multiple selectors but as not all are same events readability will suffer.
Any thoughts for improvements?
EV_ADD_CATEGORY
andEV_ENTER_KEY
? I see those constants used in some places, but - I suspect - not all the places they ought to be. \$\endgroup\$