I need to turn a lot of html elements as editable elements. You will double click on the element to edit, press enter to validate (send a PUT to the RESTapi), press esc to undo.
I've written this piece of code. Are there any performance improvements to be made?
var editable = (function() {
var DELAY = 300,
clicks = 0,
timer = null;
var addEditDelegateEvents = function(element, selector, url, idInUrl, idAttr, ajaxAttr) {
// disable the double click, and handle it in the single click envent
element.on("dblclick", selector, function(event) {
event.preventDefault();
});
element.on("click", selector, function(event) {
event.preventDefault();
var href = $(this).attr('href');
clicks++; //count clicks
if (clicks === 1) { // single click action
timer = setTimeout(function() {
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof href !== typeof undefined && href !== false) {
window.location = href // follow hlink
};
clicks = 0; //after action performed, reset counter
}, DELAY);
} else { //double click action
clearTimeout(timer); //prevent single-click action
// double click action
//transform the double clicked element into an <input>
var originElement = $(this);
var editElement = $(document.createElement('input'));
editElement.val(originElement.text());
originElement.replaceWith(editElement);
editElement.focus();
id = originElement.attr(idAttr);
url = url.replace(idInUrl, id); //replace idInUrl in url by id
editElement.on("keypress", function(event) {
if (event.which == 13) {
//send ajax call then re-populate the list
var newVal = editElement.val();
var obj = {};
obj[ajaxAttr] = newVal;
$.ajax({
method: "PUT",
url: url,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log('sheet updated');
// Very careful here : the RESTapi should return a JSON
// with the updated infos
originElement.text(data[ajaxAttr]);
editElement.replaceWith(originElement);
},
error: function() {
console.log('error on sheet update');
editElement.replaceWith(originElement);
}
});
}
if (event.which == 27) {
editElement.replaceWith(originElement);
}
});
clicks = 0; //after action performed, reset counter
}
});
};
// public API
return {
addEditDelegateEvents: addEditDelegateEvents
}
})();
And I will register my events as:
editable.addEditDelegateEvents($("p.editable_sheet_date_end"), "span", "/api/v1/sheets/ID/update", "ID", "sheet_id", "end");
I'm aware of the weakness of my implementation of url,idInUrl,idAttr, ajaxAttr.
But my question is rather: is this a solid design? My primary goal is the speed (loading and interactions).
I will have around 1000 delegates to deal with.