现在你已经知道如何使用单一对象(singleton object)作为一个命名空间,让我们关注单一设计模式的一个特别的应用.在一个多页面的网站,通常会有所有页面都能用到的代码段.通常这些都放在扩展的文件中(*.js).同样也有一些代码只出现在某一个页面中而不出现在其它的页面中.把他们分别封装在自己的单一对象中是一个好的思想.
包装有特别代码断的单一对象不同的页面看上去有所不同.他需要封装一些数据(比如是一些常量).包含一些方法以便特殊页面的特殊应用,同时还包含一些初始化的方法。Dom中特殊的元素的code.比如事件的绑定。只能在这些相对应的元素就位之后加载之后才能起作用。通过创建一个初始化的方法(init method)同时在window 的load中执行这个方法,你能把这些初始化的方法放在一个地方。
下面是包装有特殊页面代码的单一对象的骨架。

the main code
1
var Namspace=
{};
2
3
Namspace.PageName=
{
4
5
//page constants
6
7
Constants_1:true,
8
9
Constants_2:10,
10
11
//page methods
12
13
method1:function()
{
14
15
16
17
},
18
19
method2:function()
{
20
21
22
23
},
24
25
//initialization method
26
27
init: function()
{
28
29
30
31
}
32
33
}
34
35
//invoke the initialization method after the page loads
36
37
addLoadEvetn(Namspace.PageName.init);
38
为了解释如果使用这种设计模式,我们通过实现一个web开发中常见的任务来了解这种方法。通常利用javascript功能化一个form是很理想的。

the design pattern example
1
var GiantCorp= window.GiantCorp ||
{};
2
3
GiantCorp.RegPage=
{
4
5
//contants in page
6
7
Form_ID:'reg_form',
8
9
OUPUT_ID:'reg_result',
10
11
//Form handle method
12
13
handleSumbmit: function(e)
{
14
15
e.preventDefault();//stop the normal form submission
16
17
var data=
{};
18
19
var inputs= GiantCorp.RegPage.formEl.getElementByTagName('input');
20
21
//collect the value of all the input
22
23
for (var i=inputs.length;i>=0;i--)
{
24
25
data[inputs[i].name]=inputs[i].Value;
26
27
}
28
29
GiantCorp.RegPage.sendRegistration(data);
30
31
},
32
33
sendRegistration: function(data)
{
34
35
//make an xmlhttprequest and call the displayResult()when response is already
36
37
},
38
39
displayResult: function(respose)
{
40
41
//output the response directly into the output element .we are
42
43
//assuming the server send back the formatted Html
44
45
GiantCorp.RegPage.outputEl.innerHtml=response;
46
47
},
48
49
//initialization method
50
51
init: function()
{
52
53
//get the form and output the outputelment
54
55
GiantCorp.RegPage.formEl= $(GiantCorp.RegPage.Form_ID);
56
57
GiantCorp.RegPage.outputEl= $(GiantCorp.RegPage.outputEl);
58
59
//hijack the form submisson
60
61
addEvent(GiantCorp.RegPage.formEl,'submit',GiantCorp.RegPage.handleSubmit);
62
63
}
64
65
66
67
}
68
69
//invoke the init method after the page load
70
71
addLoadEvents( GiantCorp.RegPage.init);
72
73
我们首先假定GrantCorp这个命名空间已经作为一个空的literal的对象已经被创建。如果他没有被创建。这会导致一个错误。这个错误能通过一行代码定义这个对象如果它没有.存在使用or这个布尔操作符来为这个对象提供一个初始值。
Var GiantCorp=window.GiantCorp || {};
在这个例子中,我们将两个html元素的id赋值给两个常量因为他们在执行中不会改变。
初始化方法得到这两个html元素然后将他们作为一个属性存储在单一的对象中。这样有几个好处:你能在运行的时候在这个单一的对象中添加或者移除成员。这个方法同样为form的submit事件绑定了一个方法。这样当表单提交的时候,通常的行为将被阻止(通过e.preventDefault())同时所有的表单数据将被收集并且通过ajax传给服务器端。