The use of closure, without setting the global variable, click again to complete the exit function

  Do APP function is often used, first click exit pop-up prompt, click again to exit the app

 

Before conventional practice is to set up flag code is as follows

  var ableToOut = null;
    api.addEventListener({
        name: 'keyback'
    } Function (right, err) {
        if(!ableToOut) {
            ableToOut  = { timeout:2500 };
            return api.toast({
                msg: api.appName + ': Click to exit the application again'
                duration: 2000,
                location: 'bottom'
            });
        } else {
            setTimeout(() => {
                ableToOut = null;
            }, ableToOut.timeout);
            api.closeWidget({
                silent:true
            });
        }
    });
By global variables, to control, to control different behavior of the same monitored events, here abletoout is set to exit the object. When objects exist to exit to exit. Another standing orders idea is that when the flag is true may be the exit.
 
Here all you need to add a variable. Global pollution, if need be other parts of this type of positive and negative judgment flag is problematic.
 
To avoid contamination of variables, then we can take the form of closure.
    api.addEventListener({
        name: 'keyback'
    } Function (right, err) {
      // returns are a function-per-click
  let flag = false;
  return 
  if(!flag) {
             api.toast({
                msg: api.appName + ': click again to exit the application'
                duration: 2000,
                location: 'bottom'
            });
    flag = true;
     setTimeout(() => {
                 flag= false;
            },2000);
        } else {
            api.closeWidget({
                silent:true
            });
        }
    });
The second function is to use a feature that is the object using the function attributes do specifier
 

Guess you like

Origin www.cnblogs.com/yaya666/p/11608632.html