2011-04-14 72 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(),避免這個問題。