Hello everyone, I'm writing a Rails app which includes ajax functionality using jQuery. I hope you guys could help me out here.
For example, in my /public/javascripts/application.js :
/* application.js */ ... $('.item-edit').editable('/item/update', { name : $(this).attr('name'), id : $(this).attr('id'), cancel : 'Cancel', submit : 'OK', indicator : 'Saving...', tooltip : 'Click to edit...', method : 'put', submitdata : {attribute : "name"} });
With the jEditable plugin, this code binds the registered elements for inline-editing.
So lets say I have a partial in app/views/shared/_item_info.html.erb
<!-- _item_info.html.erb -->
...
<li class="item-edit" id="<%= item.id %>"><%= item.name %> </li>
...
On first load, when any 'item-edit' elements are clicked, the user will be presented with an inline textbox with an 'Ok' button. When 'Ok' is clicked, a 'PUT' request is submitted causing that text to be saved. After that text has been saved in the DB, we will then render the new text by calling the partial:
This is what my update.js.erb looks like:
/* update.js.erb */
...
$("#items").html("<%= escape_javascript(render('shared/item_info')) %>")
$('.item-edit').editable('/item/update', {
name : $(this).attr('name'),
id : $(this).attr('id'),
cancel : 'Cancel',
submit : 'OK',
indicator : 'Saving...',
tooltip : 'Click to edit...',
method : 'put',
submitdata : {attribute : "name"}
});
...
You may have noticed that I have to re-register my elements to enable inline-editing, if not, clicking on the elements will do nothing. My problem is that I am re-registering other events in other requests such as in create.js.erb as well which causes massive code duplication.
Is there any solutions to this problem? Is there a way where I could put all my common event re-registering codes in one .js file and include it inside a create.js.erb, update.js.erb...so that all my events will be re-registered without me having to copy/paste code?
Sorry for being long-winded. Would appreciate any help I could get.