I am using a trigger call a get a value from custom event but I want it to return a value and its only giving me Object Object when I do the following call:
var
You cannot return a value from a trigger, but you can store information in many different ways, one way is using a object as a parameter:
//event
$("element").on("click", function(event, informationObj) {
informationObj.userId = 2; //you have to access a propery so you can modify the original object
});
//trigger
var informationObj = {userId : 0};
$("element").trigger("click", [informationObj ]); //informationObj.userId === 2
other way is using jQuerys .data()
method
//event
$("element").on("click", function() {
$(this).data("userId", 2);
});
//trigger
$("element").trigger("click").data("userId") //2
Another thing you can do is modifying a variable that's declared outside the event and then using it after calling the trigger, or storing it as a property in the element that has the event with the this
keyword like this:
//inside the event function
this.userId = 2;
//outside the event
$("element").trigger("click").get(0).userId
Hope it helps.
Edit:
Also, take a look at @Arm0geddon answer below, using .triggerHandler()
, just beware that it has some side effects, like not bubbling up the DOM hierarchy.