m4w Singleton

menu4web is implemented as m4w singleton object. Main benefit of this implementation is that no functions or variables are stored in global namespace. Instead they are defined as methods and properties of m4w object.

In JavaScript global object is used by default to store all variables. So if you do not declare your variables they will become global variables or properties of the global window object. Functions are instances of global Function object. This is usually not a problem for small javascript applications. For example if you just add a drop-down menu to a site, and this is the only javascript you will have on your site, having your menu in global namespace should be ok.

However if you plan to use multiple javascript libraries there is a good chance that your functions or variables will collide in global namespace. In this case it is much safer to encapsulate your variables and functions as properties and methods of a javascript object. menu4web examples show how to do it. Please view the source code to see how it is accomplished.

By default m4w object has the following properties and methods defined:

Properties:

m4w.v - version
m4w.eDO - menu open delay
m4w.eDC - menu close delay

Methods:

m4w.m - creates menu
m4w.i - creates menu item
m4w.e - creates menu element
m4w.draw - draws menus
m4w.iOver - triggers menu item over action

Object Augmentation

You can also save your own variables and functions as properties of m4w object. In javascript this is known as object augmentation. You augment an object by simply assigning new methods or properties to it. This technique allows to encapsulate your variables and functions to an isolated namespace. For example you can save your menu style into a variable:

menuStyle="position: relative; alwaysvisible: true; orientation: vertical;"

In this case menuStyle variable is global. It can potentially collide with other variables if they are named the same. However if you save it as a property of m4w object it will be limited to m4w object namespace:

m4w.menuStyle="position: relative; alwaysvisible: true; orientation: vertical;"

Keeping global namespace clean is important for large projects which may use multiple javascript libraries. To avoid collisions in the global namespace and improve reliability of your application it is recommended to encapsulate your menu variables as properties of m4w object.

Last edited Jan 1, 2013 at 4:54 PM by sn41, version 13

Comments

No comments yet.