Quantcast
Channel: WinJS – Dhananjay Kumar
Viewing all articles
Browse latest Browse all 10

What is Namespace in WinJS

$
0
0

Let us first try to understand, why we need Namespace? I will try to explain you with an example, let us suppose you have a function named GreetingMessage in JS file named Library.js

image

Now you need to use this function on default.js. When you try to call that function from other js file , you get following exception.

 

image

Essentially, you cannot access a function or variable outside its scope. Namespace in WinJS library allows you to access a function outside its scope.

  • Namespace allows you to access a function outside its scope.
  • Namespace allows you to use a function in different files along with file it is defined.
  • Namespace helps you to organize your code
  • Any type created in Namespace can be referenced outside the scope of Namespace

Now let us see that how can we define a Namespace in WinJs . You can define Namespace by calling the define function

 

image

There are two parameters need to be passed to create Namespace.

  1. Namespace name is a string
  2. Members of the Namespace as object

You can create a Namespace in Library.js as following,


(function () {

 function GreetingMessage() {

return "Hello from WinJS";

 }

WinJS.Namespace.define("MyLibrary.Function", {
 GreetingMessage: GreetingMessage
 });

})();

There are few points you need to take care here

  • Enclosed all the Namespace definition in self executed function
  • Make sure you are not forgetting the braces at the end.
  • We have defined a function named GreetingMessage
  • We have defined a namespace and function inside that can be accessed as following

image

We have defined a Namespace and now we want to access the function GreetingMessage() on the default.js file. To do this first step you need to do is to refer MyLibrary.js on default.html file. You can refer that as following,

image 
Now you can access GreetingMessage() function on default.js as following ,

var res = MyLibrary.Function.GreetingMessage();
 var output = document.getElementById("output");
 output.innerHTML = res;

In this way by using Namespace, you can access functions and objects in different files and beyond scope of the declaration. I hope you find this post useful. Thanks for reading.


Filed under: Windows Store Apps

Viewing all articles
Browse latest Browse all 10

Trending Articles