Use jQuery .trigger to call a custom function that returns a value

后端 未结 4 1314
有刺的猬
有刺的猬 2021-02-14 04:34

Is there any way using jQuery\'s .bind() and .trigger() calls to execute a user defined function (ex: save ()) and act upon the return from the method? For example:

<         


        
4条回答
  •  南旧
    南旧 (楼主)
    2021-02-14 04:43

    Why don't you act on the return value in the callback itself? It takes away the extra check (that won't work like you would expect it to).

    $("#aForm").bind ('save', function () {
      if(some stuff happens that is true) {
          doSomething();
      }
    
      else {
          doSomethingElse();
      }
    });
    

    Callbacks don't work synchronously. They are used to handle things that happen asynchronously (like events). In they context of callbacks, they are pieces of code that run when something happens. Returning values from them really doesn't make sense. In your example, since you want to check on the return value of the callback, you can be sure that you only get a return value when the callback runs (because you're trying to use them like a regular function). In that case, put that logic inside the callback itself (like I have shown above).

提交回复
热议问题