23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sidebar: WinJS.Namespace.define and WinJS.Class.define<br />

WinJS.Namespace.define provides a shortcut for the JavaScript namespace pattern. This helps to<br />

minimize pollution of the global namespace as each app-defined namespace is just a single<br />

object in the global namespace but can provide access to any number of other objects, functions,<br />

and so on. This is used extensively in WinJS and is recommended for apps as well, where you<br />

define everything you need in a module—that is, within a (function() { ... })() block—and<br />

then export selective variables or functions through a namespace. In short, use a namespace<br />

anytime you’re tempted to add any global objects or functions!<br />

The syntax: var ns = WinJS.Namespace.define(, ) where is a string<br />

(dots are OK) and is any object contained in { }’s. Also, WinJS.Namespace.-<br />

defineWithParent(, , ) defines one within the namespace.<br />

If you call WinJS.Namespace.define for the same multiple times, the are<br />

combined. Where collisions are concerned, the most recently added members win. For example:<br />

WinJS.Namespace.define("MyNamespace", { x: 10, y: 10 });<br />

WinJS.Namespace.define("MyNamespace", { x: 20, z: 10 });<br />

//MyNamespace == { x: 20, y: 10, z: 10}<br />

WinJS.Class.define is, for its part, a shortcut for the object pattern, defining a constructor so<br />

that objects can be instantiated with new.<br />

Syntax: var className = WinJS.Class.define(, ,<br />

) where is a function, is an object with the<br />

class’s properties and methods, and is an object with properties and methods<br />

that can be directly accessed via . (without using new).<br />

Variants: WinJS.Class.derive(, ...) creates a subclass (... is the same arg list as<br />

with define) using prototypal inheritance, and WinJS.Class.mix(, [])<br />

defines a class that combines the instance (and static) members of one or more other <br />

and initializes the object with .<br />

Finally, note that because class definitions just generate an object, WinJS.Class.define is<br />

typically used inside a module with the resulting object exported to the rest of the app as a<br />

namespace member. Then you can use new . anywhere in the app.<br />

128

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!