2011-04-14 98 views
0

我最近一直在看一些网站,看看他们是如何构建他们的jQuery,看着Forrst.com他们似乎有一个非常独特的使用方式。关于init的jQuery问题

以下是他们网站上的一些代码片段。

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(); 

任何人都可以解释这里发生了什么,以及以这种方式构建代码的优点是什么?谢谢

回答

0

猜测:Forrst用于母版页或某个模板,Stream用于衍生视图并具有特定的页面javascript。

0

的好处是,你的,因为你的函数是沙盒(命名空间是一个更好的词),你可以使用规范的功能名称,如init(因此称为像这样:Forrst.init()),而不是Forrst_init。这允许函数名称更清楚地指出他们将要做什么。

另外,您不要混淆全局命名空间。一个为什么这是不好的例子:如果你命名一个全局函数init,然后你尝试添加一个名为init的全局函数的jQuery插件,你会遇到问题,并且必须重写一些代码才能获得摆脱功能碰撞。使用名称空间可以调用MyPlugin.init()OtherPlugin.init(),避免这个问题。