HTML and CSS Reference
In-Depth Information
Metro JavaScript files follow three different conventions to reduce namespace pollution, all of
which you should adopt.
Creating Namespaces
The WinJS API helps reduce global namespace pollution through the define method of the
Namespace object:
WinJS.Namespace.define("ViewModel.UserData", {
// … members for the ViewModel.UserData object are defined here …
he rst argument to the define method is the global name that you want to assign to your
object. In this case, I have specified ViewModel.UserData , which creates a global variable called
ViewModel that has a UserData property. The value of the UserData property is the object that
I pass as the second argument to the define method, effectively exporting the members of the
object so that they are available globally via ViewModel.UserData . You'll see how this works
when I come to apply the data to markup shortly.
There are a couple of reasons to use the define method, as opposed to handling this your-
self. First, the ViewModel object will be created only if it doesn't already exist. This means I can
easily build up the capabilities of my view model through multiple calls to the define method.
The idea is that I can associate complex objects and functions together under a single global
namespace object and reduce the likelihood of a variable name collision.
There is a more sophisticated approach to dealing with this issue, known as the
Asynchronous Module Definition (AMD). The AMD technique effectively eliminates global variable
name collisions by allowing the consumer of a JavaScript file to pick the name of the variable
through which a JavaScript library is accessed. Metro doesn't support AMD modules directly, but
you can use an AMD-aware script loader such as require.js .
he second reason to use the define method is because it doesn't export any property that
begins with an underscore character, which is a common JavaScript convention for defining
private members. This means that when I export my UserData object, the _shoppingItems and
_preferredStores properties are not globally available. This is a nice trick, and it means that
the private implementation details of your global objects remain private, but, as you'll learn, it
does cause some mild issues with other WinJS features.
Using Self-executing Functions
The second convention is to use self-executing functions in your JavaScript files. The basic shape
of a self-executing function looks like this:
(function() {
// … statements go here …
Search WWH ::

Custom Search