Event listener firing too early when parameters are passed

落爺英雄遲暮 提交于 2019-12-02 10:45:06

问题


I pass a number of parameter to a javascript function which builds a form for the user to fill in. Among these parameters are two more functions contained in a separate class which handle the saving or canceling of the form. The cancel function requires two parameters which it uses to determine which list of entities to build. The problem lies in the parameters. While in the form building function, if I attached the cancel function to the newly created cancel button without giving it any parameter the function button works fine but builds an empty list due to the lack of parameters. However if I attach the function with the parameters, the function fires right away when the page is created rather than when the button is clicked. I have tried attaching the listener in a couple different ways including javascript, jquery and even yahoo.util. Everything works correctly in the cancel function when it is called with parameters in other instances. Any ideas on why the function fires to early when parameters are passed?

Here is some sudo code of different ways I have attached the even listener.

function buildform(formData, saveFunction, CancelFunction, p1, p2){
      $("#cancelButton").live("click", cancelFunction(p1, p2);
      YAHOO.util.Event.on("cancelButton", "click", cancelFuntion(p1, p2));
      cancelButton.setAttribute("onClick",cancelFunction(p1, p2);
}

回答1:


You have to wrap your method calls in function blocks, otherwise they are evaluated immediately:

$("#cancelButton").live("click", function () { cancelFunction(p1, p2); });


来源:https://stackoverflow.com/questions/10758466/event-listener-firing-too-early-when-parameters-are-passed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!