简体   繁体   English

块函数在javascript中作为参数传递时运行

[英]block function run when it is passed as parameter in javascript

var event = function(id) {
    alert(id);
}

textProgressBar.generator('20', text1, event("test"));

this.generator = function (percentage, text, event, type) {
    ....
    $(this.id).children().last().on('click', event);
}

I want to run function when it is clicked. 我要在单击时运行功能。 But it's function run when page is loaded. 但是它的功能在页面加载时运行。

textProgressBar.generator('20', text1, event("test"));

If I pass the parameter to event function, it run when page is loaded. 如果我将参数传递给event函数,则它将在页面加载时运行。

How can I block this function when page is loaded? 页面加载后如何阻止此功能?

This line: 这行:

textProgressBar.generator('20', text1, event("test"));

calls event and passes its return value into textProgressBar.generator , exactly the way foo(bar()) calls bar and passes its return value into foo . 调用 event并将其返回值传递给textProgressBar.generator ,这与foo(bar()) 调用 bar并将其返回值传递给foo的方式完全相同。

If you want to pass the function into generator , you'll need to pass a function reference rather than calling the function. 如果要将函数传递给generator ,则需要传递函数引用而不是调用函数。

Two ways to do that: 有两种方法:

  1. A wrapper function: 包装函数:

     textProgressBar.generator('20', text1, function() { event("test"); }); 

    There, we create a function (an anonymous one) that, when caled, will call event passing in "test" as an argument. 在那里,我们创建了一个函数(一个匿名函数),该函数在经过校准后将调用传入"test" event作为参数。

  2. Function#bind : Function#bind

     textProgressBar.generator('20', text1, event.bind(null, "test")); 

    Function#bind creates a new function that, when called, will call the original with a given this value ( null in my example) and any arguments you give bind ( "test" in my example). Function#bind创建一个新函数,该函数在被调用时将使用给定的this值(在我的示例中为null )以及您给其bind任何参数(在本示例中为"test" )调用原始函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM