I have a question regarding developing object-orientated javascript and parsing variables. Please see this blog by net.tutsplus - The Basics of Object-Oriented JavaScript for more info.
I have the following code which creates an event:
$(document).ready(function() {
tools.addEvent('.someButton', 'click', user.getUserDetails);
)};
var tools = {
addEvent: function(to, type, fn) {
$(to).live(type, fn);
}
}
var user = {
getUserDetails: function(userID) {
console.log(userID);
}
}
As you can see, it calls the addEvent method with three variables; the DOM element to attach the event to, the type of the event and the function to run when the event is triggered.
The issue I am having is parsing a variable to the getUserDetails method and I know of 2 options:
I could obviously have 1 line of code at the start which could check an attribute of the sender. For example, the
.someButtoncould have an attributeuserID="12345". However, this is not ideal because the function is run from several different places - meaning this check is not always available (and the code is harder to manage).A better option could be to have another method like
user.willGetUserDetailsand use this method to get the attributeuserIDfrom the DOM. This could be run from anywhere on the page, and would callgetUserDetailsafter getting theuserID. Whenever the user details comes from within another function, we would simply callgetUserDetailsdirectly.What would be ideal, is if I could amend the code above to pass a variable directly - even an undefined one. Does anyone know how this could be achieved?
JSON.stringify(variable);. Also, do not use.live()since it was removed from jQuery since 1.9