Jquery: Returning Value From Trigger

后端 未结 6 798
轮回少年
轮回少年 2021-02-02 10:14

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          


        
6条回答
  •  佛祖请我去吃肉
    2021-02-02 10:24

    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.

提交回复
热议问题