如何解决有关init的jQuery问题
| 我最近一直在浏览一些网站,以了解它们如何构造jQuery,并在Forrst.com上,他们似乎拥有一种非常独特的使用方式。 这是他们网站上的一些代码片段。Forrst = {
showingTopClicker: false,currentUserID: -1,formKey: \"\",init: function () {
$(document).ready(function () {
Forrst.formKey = $(\"meta[name=forrst-form-key]\").attr(\"content\");
Forrst.currentUserID = $(\"meta[name=forrst-userid]\").attr(\"content\");
Forrst.applyLibs();
Stream.init();
$(\"#promo-excerpt\").jTruncate({
length: 95
});
$(\".notice-bar a.close\").click(function () {
return Forrst.hideNoticeBar()
});
PostForm.init();
People.init();
Comments.init();
Stream = {
isLoading: false,streamPath: \"\",pageBy: \"after\",afterID: false,page: 1,extraParams: {},init: function () {
if ($(\"#stream\").length == 0) {
return
}
Stream.redirectFromHash();
$(\".post-toggle > a\").live(\"click\",function () {
$(this).parent().parent().children(\".post\").toggle(\"fast\");
$(this).parent().hide();
return false
});
$(window).scroll(function () {
if (($(document).height() - $(window).height()) - $(window).scrollTop() <= 300) {
Stream.loadMore()
}
})
},redirectFromHash: function () {
if (window.location.hash != null && window.location.hash != \"\" && window.location.hash.match(/^#?after:/i)) {
var b = window.location.pathname.split(\"/\");
var c = \"\";
Forrst.init();
谁能解释这里发生了什么以及以这种方式构建代码的好处是什么?谢谢
解决方法
猜猜:Forrst用于母版页或某些模板中,Stream用于派生视图中,并且具有特定页面的javascript。
,优点是您可以使用函数,因为您的函数是沙盒化的(命名空间是一个更好的词),因此可以使用诸如function1ѭ(因此被称为:2ѭ)之类的规范函数名称,而不是
Forrst_init
。这使函数名称可以更清楚地指示它们将要执行的操作。
此外,您不会使全局名称空间混乱。为什么这样做不好的一个例子:如果您命名一个全局函数init
,然后稍后您尝试添加一个带有名为init
的全局函数的jQuery插件,您将遇到问题,必须将某些代码重写为摆脱功能冲突。使用命名空间,您可以调用MyPlugin.init()
和OtherPlugin.init()
,避免出现此问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。