【发布时间】:2013-01-02 12:43:50
【问题描述】:
考虑到Code Organization section of the Learning Center 中发布的关于模块模式的最后一个代码片段(如下所述),我试图了解示例中模块的某些方面:
- 变量声明(
$items,$container...)由;分隔,而函数声明(createContainer,buildUrl,showItem,...)由@分隔987654328@。为什么?有括号问题吗? - 为什么前三个变量(
$items、$container和$currentItem)的名称以$开头?这是否意味着用于标识 DOM 片段变量的命名约定(因为javascript允许使用字符$)还是有其他原因? - 为什么函数
createContainer使用var声明,而其他函数(buildUrl、showItem、...)没有var?
// 将模块模式用于 jQuery 功能 $( 文档 ).ready(function() {
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 );
});
【问题讨论】:
标签: jquery code-organization module-pattern