0

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);

3 Answers 3

2

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);
};
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Demo

Comments

0

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.

http://jsfiddle.net/MWxG8/

3 Comments

When you do this: myF(myCar) you are calling that function at that moment. That will not add the handler to the click function
this calls the function before the click
you'd need to return a function and not call the alert directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.