Search code examples
javascriptjquerycode-maintainability

Events in Object variables


Can you place a jQuery event inside of an object variable like so:

var taskObj = {
    buttonClick:function() {
        $("#button").click(function() {
            alert("Something");
        )};
    }
}

If so how would you call it the method? Could I possibly bind it to an event? Reason I'm asking is because I'm trying to change some spaghetti code (alot) and make it a bit easier to maintain without having to rewrite it all. Any insight would be much appreciated.


Solution

  • Yes, you can do that. Your current object only has a click handler, so to actually bind it just run:

    taskObj.buttonClick();
    

    On DOM ready. To have an object hold the functions for handlers, you could do:

    var taskObj = {
        buttonClick:function() {
            alert("Something");
        }
    }
    

    And define the handler as:

    $("#button").click(taskObj.buttonClick);