tags:

views:

107

answers:

4

i have a javascript function

how to check

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

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

like require_once or include_once with php

help me thank

+2  A: 
var called = false;
function blah() {
   called = true;
}

if ( !called ) {
   blah();
}
meder
For those global-variable-nazis [since this is in the global scope], you can use blah.called instead of var blah... assuming blah is already defined. This code is pretty enough for me, though.
ItzWarty
The disadvantage of this pattern is that you have to wrap the function call in a conditional statement everywhere it gets invoked.
Török Gábor
+3  A: 

That's easy to accomplish, as javascript functions are objects that can have members and properties:

var callMeOnlyOnce=function(){

    if(this.alreadyCalled)return;

    alert('calling for the first time');

    this.alreadyCalled=true;
};

// alert box comes
callMeOnlyOnce();


// no alert box
callMeOnlyOnce();

EDIT:

As pointed out correctly by CMS, using this is not that easy. Here's a revised version that uses a custom namespace instead of this.

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();
seanizer
The `this` value refers to the Global object, not to the function itself, and `allreadyCalled` will end up being a property of the Global object. This is because the function has been invoked from a reference that doesn't have a base object: `callMeOnlyOnce();`. [More info on `this`](http://stackoverflow.com/questions/3320677/this-operator-in-javascript/3320706#3320706)
CMS
+2  A: 

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
Török Gábor
A: 
If (!your_func.called) {
    your_func.called = true;
    your_func();
}
Thevs