waspinator
waspinator

Reputation: 6826

how do I pass data into an jquery .on() function

I'm trying to pass in an object into an .on() function, but I can't figure out how to do it.

element_number = 1;

$('#button0').on('click', function () {
    // how do I pass this object into the data parameter of the next .on function?
    object = {
        name: "abc",
        number: element_number
    };
    $('#from-static').append(
        '<button class="btn" >' + 'Element #' + element_number + '</button> <br/>');
    element_number = element_number + 1;
});

// function to handle dynamically generated buttons
$(document).on('click', '.btn', data, function (event) {
    // how do I get the object data from last function?

    // show element number
    alert(event.data.object.number);

});

http://jsfiddle.net/waspinator/5RgWh/4/

Upvotes: 1

Views: 235

Answers (2)

luke1985
luke1985

Reputation: 2354

You can't pass data to "on" function because this function only registers a callback.

You must hold data elsewhere and read the data when the event happens.

If you are really eager to do "your" way, you can use lexical scoping:

var aPerson = {
  name: "Matthew",
  age: 21
}

$('#button0').on('click', function () {
    // how do I pass this object into the data parameter of the next .on function?
    alert(aPerson.age); // works fine.
});

Upvotes: 1

Niels
Niels

Reputation: 49919

You can do this (example: http://jsfiddle.net/5RgWh/7/ ):

element_number = 1;

$('#button0').on('click', function () {
    // how do I pass this object into the data parameter of the next .on function?
    object = {
        name: "abc",
        number: element_number
    };
    var jqBTN = $('<button class="btn" >' + 'Element #' + element_number + '</button> <br/>');
    jqBTN.data("objectdata", object);
    $('#from-static').append(jqBTN);
    element_number = element_number + 1;
});

// function to handle dynamically generated buttons
$(document).on('click', '.btn', function (event) {
    // how do I get the object data from last function?

    var object = $(this).data("objectdata");
    // show element number
    alert(object.number);

});

Save it in the jQuery data storage of the element.

Upvotes: 2

Related Questions