考虑关于发表在Code Organization section of the Learning Center模块模式的最后一个代码段(下面报道),我试图理解在示例中,模块的某些方面:了解jQuery的教程模块模式例如
- 的变量声明(
$items
,$container
...)由;
分开,而函数声明(createContainer
,buildUrl
,showItem
,....)由,
分隔。为什么?有支架问题吗? - 为什么前三个变量的名称(
$items
,$container
和$currentItem
)以$
开头?这是否意味着命名约定(因为javascript
允许字符$
)用于标识DOM片段变量或者是否存在其他原因? - 为什么函数
createContainer
使用var
声明,而其他函数(buildUrl
,showItem
,...)没有var
?
//使用模块模式的一个jQuery功能 $(文件)。就绪(函数(){
var feature = (function() {
var $items = $("#myFeature li");
var $container = $("<div class='container'></div>");
var $currentItem = null;
var urlBase = "/foo.php?item=";
var createContainer = function() {
var $i = $(this);
var $c = $container.clone().appendTo($i);
$i.data("container", $c);
},
buildUrl = function() {
return urlBase + $currentItem.attr("id");
},
showItem = function() {
var $currentItem = $(this);
getContent(showContent);
},
showItemByIndex = function(idx) {
$.proxy(showItem, $items.get(idx));
},
getContent = function(callback) {
$currentItem.data("container").load(buildUrl(), callback);
},
showContent = function() {
$currentItem.data("container").show();
hideContent();
},
hideContent = function() {
$currentItem.siblings().each(function() {
$(this).data("container").hide();
});
};
$items.each(createContainer).click(showItem);
return {
showItemByIndex: showItemByIndex
};
})();
feature.showItemByIndex(0);
});