2012-01-25 36 views
2

我寫了一點簡單的用戶界面的東西今天我只能夠使用jQuery的項目,沒有主心骨,KnockoutJS等..緩存選擇使用jQuery

所以,基本上我寫了一些對象看起來像這樣十歲上下...

var UI = UI || {}; 
UI.login = (function($){ 
    function Welcome(){ 
     this.firstName = $("#firstName"); 
     this.lastName = $("#lastName"); 
     this.email = $("#email"); 
     this.password = $("#password"); 

     this.message = $("#message"); 

     this.init(); 
    } 

    Welcome.prototype.init = function(){ 
     this.email.bind('blur', $.proxy(this.checkEmail, this)); 
     // etc..etc... 
    }; 

    Welcome.prototype.checkEmail = function(event){ 
     var email = $(event.currentTarget).val();  

     if(!checkEmail(email)){ 
      this.message.html('This email is invalid.') 
       .show(); 
     } 
    }; 

    function checkEmail(email){ 
     // do dome validation 
     return isValid; 
    } 
    // etc.. etc... 

    return Welcome; 
}(jQuery)) 

我的問題是...在歡迎構造緩存的選擇是好還是壞主意?此外,我想也許只是得到這種模式的一些反饋...

謝謝!

+1

您將不會從緩存''#id''選擇器結果中獲得任何切實的性能優勢,它們被優化爲使用'document.getElementById'。 – Esailija

+0

是的,非常真實。 – scottheckel

回答

1

如果您在整個程序中重複使用,那很好。我以前做過很多次了。親是你不必爲了節省你一些執行時間而重新選擇這些選擇器;然而,它是better to chain methods in jQuery(或者我已經讀過......這不是一個很大的差異IMO,你應該總是優化性能時最後,如果這意味着犧牲代碼質量)。其中一部分原因是你通過創建這些可能或不可以使用的jQuery對象而受到打擊。

還有一點需要注意的是,使用局部變量會提高性能,但通常保存這些jQuery對象會比非本地變量更好。