Patrick
Patrick

Reputation: 7185

Object-Oriented Javascript custom addEvent method

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:

  1. I could obviously have 1 line of code at the start which could check an attribute of the sender. For example, the .someButton could have an attribute userID="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).

  2. A better option could be to have another method like user.willGetUserDetails and use this method to get the attribute userID from the DOM. This could be run from anywhere on the page, and would call getUserDetails after getting the userID. Whenever the user details comes from within another function, we would simply call getUserDetails directly.

  3. 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?

Upvotes: 2

Views: 183

Answers (1)

Kevin B
Kevin B

Reputation: 95022

Add one more argument to your addEvent code that accepts data to pass to the event.

var tools = {
    addEvent: function(to, type, data, fn) {
        if ($.isFunction(data)) {
            fn = data;
            data = {};
        }
        $(to).live(type, data, fn);
    }
}

Also, i'd suggest using delegate instead, or .on in 1.7+

var tools = {
    addEvent: function(to, type, data, fn) {
        if ($.isFunction(data)) {
            fn = data;
            data = {};
        }
        $(document).delegate(to, type, data, fn);
    }
}

or

var tools = {
    addEvent: function(to, type, data, fn) {
        if ($.isFunction(data)) {
            fn = data;
            data = {};
        }
        $(document).on(type, to, data, fn);
    }
}

Now you can use it like this:

$(document).ready(function() {
    tools.addEvent('.someButton', 'click', {userID: theuserid}, user.getUserDetails);
)};

var user = {
    getUserDetails: function(event) {
        console.log(event.data.userID);
    }
}

Upvotes: 4

Related Questions