The Question: Here is how I am passing data with js. Is this a good way to go about it or am I doing it wrong? It does work but it seems... suspicious, I suppose, to my relatively noob JS skills.
I have a custom grid plugin that generates a grid of data. Let's say it generates rows of user names with their id #, role, some dates, etc.
I want to be able click an "edit" link in each row that pops up a modal window to manage the data. Perhaps change a user's role.
The grid is generated by code wrapped in an anonymous function and the modal is generated by code wrapped in a different anonymous function. I need to populate the modal with the correct data for that particular clicked row.
What I have done is include the necessary data as custom attributes in the link that is clicked to manage that user's data. The generated link looks something like this:
<a href="#" userrole="role1" userid="12345"> Manage </a>
So clicking that link will launch the modal window and then I use some jquery to grab the attribute values and populate the modal. An example:
First, the code that handles the click (just assume that click handlers and other document.ready() stuff is assigned... I left that out for brevity but this is based on code that works correctly):
(function(){
var EditUserClick = function(e) {
userRole = $(this).attr('userrole'); //assign some values
userId = $(this).attr('userid'); // assign some values
OpenEditUserModal(userRole,userId);
}
});
Second, the code that handles the modal:
//Public stuff so it's accessible to the click.
var OpenEditUserModal;
(function(){
OpenEditUserModal = function(userRole,userId){
//code to handle the modal window opening can go here
//populate the modal
$('#userRole').text(userRole); // let's say this is a text field
$('#userId').val(userId); //let's say this is a hidden form field
}
});
So how about it? Is there a better way to get this data passed around than assigning it to made-up link attributes and passing it onclick to the next method? Any other advice is welcomed... always looking to learn.