closures

How do I reuse this JavaScript timeout closure?

喜夏-厌秋 提交于 2019-12-06 13:51:37
I found the following piece of JavaScript code (maybe here at Stack Overflow?) for implementing a timeout: var delay = (function() { var timer = 0; return function(callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); I'm new to JavaScript, so I'm still trying to wrap my head around closures. If I call delay(firstCallback, 200) in one place and then delay(secondCallback, 200) right after, the first timeout callback is cleared, while the second callback executes successfully. How do I reuse delay in different instances without overwriting other instances? (Not sure if

Removing event listeners with anonymous function calls in JavaScript

梦想的初衷 提交于 2019-12-06 12:54:38
I'm trying to remove an event listener for created span elements where the function called is within a closure. I've tried various methods and none seem to work. var MyClass = function () {} MyClass.prototype.addSpan = function (el) { var span = document.createElement('span'); span.innerHTML = "Text here"; el.appendChild(span); span.addEventListener('click', (function (obj) { return function () { obj.removeSpan(); } })(this), false); } MyClass.prototype.removeSpan = function () { alert('removing span'); this.removeEventListener('click', arguments.callee, false); // .... remove span .... }

Groovy: how to call closure in top scope from another closure

时间秒杀一切 提交于 2019-12-06 12:42:35
I'm trying to break up code that makes use of the Jenkins Job DSL plugin into reusable pieces, and I suspect that my question is generic to Groovy and not Jenkins-specific. For example, I want to reuse parts of this block: freeStyleJob() { //generic stuff name "something" description "something else" //custom stuff scm { svn { //etc.... } } } By placing name and description in a utility method (obviously I want to do more than just that in real life). However, I cannot find the proper syntax to create a closure for the current scope. Here is how I think it should look: def jobCommonItems() {

Storing an unboxed closure with a reference arg in a HashMap

感情迁移 提交于 2019-12-06 12:16:28
I'm trying to store a closure as a HashMap value. If I pass the closure arg by value, everything works great: use std::collections::hash_map::HashMap; fn main() { let mut cmds: HashMap<String, Box<FnMut(String)->()>> = HashMap::new(); cmds.insert("ping".to_string(), Box::new(|&mut:s| { println!("{}", s); })); match cmds.get_mut("ping") { Some(f) => f("pong".to_string()), _ => () } } ( playpen ) But if I want a closure that takes a reference arg, things go south: use std::collections::hash_map::HashMap; fn main() { let mut cmds: HashMap<String, Box<FnMut(&str)->()>> = HashMap::new(); cmds

Why Don't Variables Reset in a Closure (Javascript)

半腔热情 提交于 2019-12-06 12:11:39
问题 I've been trying to learn about closures, but one thing still perplexes me. If I have the following code: var add = (function () { var counter = 0; return function () {return counter += 1;} })(); add(); add(); add(); // Returns "3" If I call add() three times, why dosen't it set counter to zero every time, then return the anonymous funtion that increments counter by one? Does it skip over it once the self-invoking function runs? Sorry if the question seems simple, I'm having a hard time

can you say this is a right example of Javascript Closure.. Where the places we need to consider avoiding the closures?

自闭症网瘾萝莉.ら 提交于 2019-12-06 11:31:10
Problem & Reason One of my team mate ended up in messy situtaion implementing function hooking in javascript. this is the actual code function ActualMethod(){ this.doSomething = function() { this.testMethod(); }; this.testMethod = function(){ alert("testMethod"); }; } function ClosureTest(){ var objActual= new ActualMethod(); var closeHandler = objActual.doSomething; closeHandler(); closeHandler.apply(objActual,arguments); //the fix i have added this.ActualTest = function() { alert("ActualTest"); }; } In the above code, var closeHandler is created in the context of ClosureTest(), but it holds

Is there a way to make this slideshow move automatically?

一世执手 提交于 2019-12-06 11:29:13
问题 This is the slideshow that we used: http://www.littlewebthings.com/projects/blinds/ and this is the JS file: http://www.littlewebthings.com/projects/blinds/js/jquery.blinds-0.9.js However, this slideshow doesn't have a setting that makes it go through each image automatically. You still have to click on the numbers below it to see the images. Does anybody know what to add into the javascript code to make it go through each image automatically? Thanks! 回答1: This solution uses closures and

JS Pass parameters as variables to an anonymous function and invoke it later -> parameter value problem

家住魔仙堡 提交于 2019-12-06 11:23:43
问题 I have a problem calling an anonymous function with parameters passed as variables. If I save an anonymous function into an array after passing it a variable as parameter, then I change the variable and invoke the function, it prints the last value of the variable, not the value of the variable at the moment I pushed the anonymous function into my array. I simplify my code in the following example: var arr = []; function myFunction(index) { alert(index); } function doPush() { var k = 'hello';

Same name (and signature) closure & function: non-ambiguous for >0 arguments, giving closure precedence when calling

两盒软妹~` 提交于 2019-12-06 10:09:16
Precedence rules for same name and signature function & closure When defining a closure and a function with same name (say, foo ) and signature, it seems as if the closure takes precedence when calling said (seemingly ambiguous) foo . // Int -> () function func foo(num: Int) { print("function \(num)")} // Int -> () closure let foo: (Int) -> () = { print("closure \($0)")} /* or... let foo = { (num: Int) in print("closure \(num)")} */ foo(1) // closure 1 If I option-click the two declarations, they point at each other under the label Related declarations , differing in how they are referred to

Usage of closures with multiple arguments in swift

流过昼夜 提交于 2019-12-06 07:07:09
This question is largely based on this one: Link The main difference being that I want to pass in arguments to the closure as well. Say I have something like this: func someFunctionThatTakesAClosure(completionClosure: (venues: Dictionary<String, AnyObject>, error: NSError) -> ()) { // function body goes here var error: NSError? let responseDictionary: Dictionary<String, AnyObject> = ["test" : "test2"] completionClosure(venues: responseDictionary, error: error!) } No error here. But when I call this function in my main view controller I have tried several ways but all of the result in different