考慮關於發表在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);
});