开发者

how to detect a function was called with javascript

I have a ja开发者_开发百科vascript function.

How to check:

  • if function was called ( in <head></head> section have this function), then not to call the function

  • if function was not called ( in <head></head> section haven't this function), then call the function

like require_once or include_once with PHP


Static variables

Here's how to create static (like in C) variables using self calling functions to store your static variables in a closure.

var myFun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I've been called");
      called = true;
    }
  }
})()

Abstract the idea

Here's a function that returns a function that only gets called once, this way we don't have to worry about adding boiler plate code to every function.

function makeSingleCallFun(fun) {
  var called = false;
  return function() {
    if (!called) {
      called = true;
      return fun.apply(this, arguments);
    }
  }
}

var myFun = makeSingleCallFun(function() {
  console.log("I've been called");
});

myFun(); // logs I've been called
myFun(); // Does nothing


Use decorator pattern.

// your function definition
function yourFunction() {}

// decorator
function callItOnce(fn) {
    var called = false;
    return function() {
        if (!called) {
            called = true;
            return fn();
        }
        return;
    }
}

yourFunction(); // it runs
yourFunction(); // it runs    
yourFunction = callItOnce(yourFunction);
yourFunction(); // it runs
yourFunction(); // null

This solution provides a side-effect free way for achieving your goal. You don't have to modify your original function. It works nice even with library functions. You may assign a new name to the decorated function to preserve the original function.

var myLibraryFunction = callItOnce(libraryFunction);
myLibraryFunction(); // it runs
myLibraryFunction(); // null
libraryFunction(); // it runs


var called = false;
function blah() {
   called = true;
}

if ( !called ) {
   blah();
}


You can use a global variable in a custom namespace to store whether the function has been called.

if(!window.mynamespace){
    window.mynamespace={};
}

mynamespace.callMeOnlyOnce=function(){

    if(mynamespace.alreadyCalled)return;

    alert('calling for the first time');
    mynamespace.alreadyCalled=true;
};

// alert box comes
mynamespace.callMeOnlyOnce();


// no alert box
mynamespace.callMeOnlyOnce();


If (!your_func.called) {
    your_func.called = true;
    your_func();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜