Basj
Basj

Reputation: 46381

Call a function of a library, outside the library

I have a library that runs in a (function() { ... }) (); scheme ...

// mylibrary.js
(function() {
    function myfunc() { alert('hello'); };

    if (...) 
      return;

    // do something

}) ();

... that I use in a HTML page :

<!DOCTYPE html> 
<html lang="en"> 
<body>  
  <div>Bonjour</div>

  <script src="mylibrary.js"></script>

  <script>
    myfunc();  // scope error !
  </script>

</body>
</html>

How to call the function myfunc() outside the library ? Should I change the (function() { ... }) (); scheme ? (that I used to be able to do some return inside the library)

What is the most common practice?

Upvotes: 2

Views: 490

Answers (3)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

You want the Revealing Module Pattern:

var module = (function() { // Self invoking function
    var privateVariable = 42; // This variable is private to the module.
    var publicFunction = function() { console.log(42); } // Still not public

    return {
        myPublic: publicFunction // Now it is, notice optional the name change!
    }
})(); //Call itself.

module.myPublic(); // Call by the new name.

In this case, the function is executed and an Object is returned (so module is now an Object), and you simply call functions which are members of that object.

Upvotes: 1

Born2Code
Born2Code

Reputation: 1075

here is how you should do it.

var myApp = (function() {
  var stuff = []; //private

  return { //exposed to public
    myfunc: function(values) {
      alert('You said: ' + values);
    }
  }
}());

myApp.myfunc('Test Me');

Upvotes: 1

20twoes
20twoes

Reputation: 27

If you mean for you function to be globally available, then you can assign it to the window object:

window.myfunc = myfunc;

This is what Mixpanel does:

http://cdn.mxpnl.com/libs/mixpanel-2-latest.js

Upvotes: -1

Related Questions