0

I have an object that I need to pass to a function, this function is trigger via onClick and onKeyUp(), but I couldn't make it work.
Although I can pass values to it.

function myFunc(myObj) {

 $("<button type="button" onclick='otherFunction( $(\"#elem\").val() )'
onkeyup='otherFunction( $(\"#elem\").val() )'> CLICK IT </button>"
} 

As you can see, i have a otherFunction and I Can pass the $("#elem").val() as a parameter. But I need to also pass myObj to it.
Tried everything I could think of and I was unable to make it work.

Obs: myObj is a marker from googleMaps, so I can't just pass it's attributes values. I need to access the full object on my second function. Because I need to do something like: myObj.setOptions(.....)

PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90
  • I think your script is not proper so if you write it clearly then i can help you. – Pankaj Bisht Feb 21 '18 at 12:22
  • @pankaj98 Not sure how to do that. It's a javascript function that uses jquery to create a button with `onclick` and `onkeyup` in it. And I'm having difficult passing the parameter because it's an object and not just a string. – PlayHardGoPro Feb 21 '18 at 12:24

2 Answers2

3

As you are using jQuery to create button, use .on() to bind event handler's. The object myObj will be accessible in the event handler due to closure

function myFunc(myObj) {
    var button = $('<button>', {
            "type": "button",
            "text": "CLICK IT"
        }).on('click keyup', function () {
            // myObj will be accessible here
            otherFunction($("#elem").val());
        });
}

A good read How do JavaScript closures work?

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

this code explained how you send data to the handler with jQuery

$('yourElement').click(yourData, function(eventObject){
    var thisIsYourData = eventObject.data;
})
LPZadkiel
  • 561
  • 1
  • 3
  • 16