OpenLayers学习10-控制台Console语言Lang

OpenLayers.Console和OpenLayers.Lang就是俩对象, 不是类
OpenLayers.Console通过自执行函数扩展, 配合firebug.js模拟了firebug控制台

OpenLayers.Lang维护一个key-value字典,
需要i18n时候, 去这个字典取对应值

一:console

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//自执行函数extend扩展Console
//在此之前OpenLayers.Console
(function() {
//检查所有scripts标签, 如果包含"firebug.js"就执行扩展
var scripts = document.getElementsByTagName("script");
for(var i=0, len=scripts.length; i<len; ++i) {
if(scripts[i].src.indexOf("firebug.js") != -1) {
if(console) {
OpenLayers.Util.extend(OpenLayers.Console, console);
break;
}
}
}
})();

二: 语言类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//语言类
OpenLayers.Lang = {
//当前语言的code
code: null,
//默认是英文
defaultCode: "en",
//没code就先set一下, 有就直接返回
getCode: function() {
if(!OpenLayers.Lang.code) {
OpenLayers.Lang.setCode();
}
return OpenLayers.Lang.code;
},
//设置code
setCode: function(code) {
var lang;
if(!code) {
//从navigator中取language
code = (OpenLayers.BROWSER_NAME == "msie") ?
navigator.userLanguage : navigator.language;
}
//拆解组装key
var parts = code.split('-');
parts[0] = parts[0].toLowerCase();
//OpenLayers.Lang[key] = {}
if(typeof OpenLayers.Lang[parts[0]] == "object") {
lang = parts[0];
}
if(parts[1]) {
var testLang = parts[0] + '-' + parts[1].toUpperCase();
if(typeof OpenLayers.Lang[testLang] == "object") {
lang = testLang;
}
}
//没有取到, 用默认值
if(!lang) {
OpenLayers.Console.warn(
'Failed to find OpenLayers.Lang.' + parts.join("-") +
' dictionary, falling back to default language'
);
lang = OpenLayers.Lang.defaultCode;
}
OpenLayers.Lang.code = lang;
},
//翻译,
translate: function(key, context) {
var dictionary = OpenLayers.Lang[OpenLayers.Lang.getCode()];
//根据key去取value
var message = dictionary && dictionary[key];
if(!message) {
//没取到value, 就返回key
message = key;
}
if(context) {
message = OpenLayers.String.format(message, context);
}
return message;
}
};
//i18n
OpenLayers.i18n = OpenLayers.Lang.translate;