Reputation: 9555
I have this all wrong and its not working.
I'm trying to call one shared function to alert data passed that is called from two different click events but |I get underfined in the alert. Why do I get underfined?
var myF = function(){
alert('a click ' + this.model + ' ' + this.year); // meant to alert the properties of the object passed to it
alert(this.ID); // meant to alert the ID of the click that called it
};
var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
var myCar2 = mycar;
myCar2.make = "VW";
myCar2.model = "golf";
myCar2.year = 2000;
$('.feature1').click(myCar,myF);
$('.feature2').click(myCar2,myF);
Upvotes: 0
Views: 536
Reputation: 3634
You get undefined
because the this
variable is the jquery anchor object. What would work in your case is
var myF = function(car){
alert('a click ' + car.model + ' ' + car.year);
};
var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
var myCar2 = new Object();
myCar2.make = "VW";
myCar2.model = "golf";
myCar2.year = 2000;
$('.feature1').click(function() { return myF(myCar); });
$('.feature2').click(function() { return myF(myCar2); });
This is not the optimal way to do it, but it will get it working.
Upvotes: 0
Reputation: 288130
To access the data in the event handler, you must use event.data
:
var myF = function(e){
alert('a click ' + e.data.model + ' ' + e.data.year);
alert(this.id);
};
Moreover, the property which contains the id is called id
, not ID
. And you have the typo myCar2 = mycar
instead of myCar2 = myCar
.
Upvotes: 1
Reputation: 4531
In the callback, "this" refers to the element where you did the click. That function will receive your custom objects in the event parameter.
You could do it like this:
$('.feature1').click({myModel: myCar}, myF);
var myF = function(e){
var data = e.data.myModel;
alert('a click ' + data.model + ' ' + data.year);
};
Upvotes: 2