2013-02-27 58 views
1

什麼模式都可以在一個大型的JavaScript應用程序重複再利用緩存很多jQuery選擇?大型jQuery選擇緩存

已經有很多談到存儲簡單的功能裏面簡單變量jQuery選擇,但一個JavaScript對象內,例如在流行的模塊模式,怎麼能一個乾淨的設置,並將其儲存?

我最初的嘗試是使用全局變量,但弄髒的命名空間,並可能導致衝突。我的第二次嘗試參與存儲對象的相應對象中的文字中的選擇,但是這會導致對他們的時間長於所需的調用,例如:

var Module = { 

    nodes: {}, 

    storeSelectorsInCache: function() { 
    Module.nodes = { 
     form: $('#form'), 
     grid: $('#grid') 
    }; 
    }, 

    initialize: function() { 
    Module.storeSelectorsInCache(); 

    // notice the long hierarchy to get to Module.nodes.form 
    Module.nodes.form.submit(function() { 
     // event handler 
    }); 
    } 

}; 

必須有一個更清潔的速記在某處。

+0

你可以指定'Module.nodes'給一個變量與一個簡短的名稱,之後使用該變量。 – 2013-02-27 16:22:02

+1

或者你可以在IIFE內工作,那麼只需使用普通的變量,從而避免污染全局命名空間,同時允許您爲您的變量使用較短的名字更容易。 – 2013-02-27 16:39:57

+0

簡單(模塊)局部變量有什麼問題? – Bergi 2013-02-27 16:42:58

回答

4

喜歡的東西,這可能是冷靜:

var _nodes = {}; 

var Module = { 
    /** 
    * You could call this when you want to query a selector and store it for reuse. Then 
    * just use this for querying. 
    * 
    * @param {String} selector The selector to memoize. 
    * @param forceUpdate {Boolean} jQuery selectors don't update with their DOM 
    *  counterparts. This will take that into account. Pass in true to override cache. 
    * 
    * @return {Object<Array<jQuery>>} The matching selectors. 
    */ 
    $: function(selector, forceUpdate) { 
    if (forceUpdate === true || !({}).hasOwnProperty.call(_nodes, selector)) { 
     _nodes[selector] = jQuery(selector); // Not that robust, just a basic example 
    } 
    return _nodes[selector]; 
    }, 

    initialize: function() { 
    this.$('#form').submit(function() { /* ... */ }); 
    } 
}; 

所以每次查詢,利用局部範圍的Module.$功能的選擇時間節點對象,將緩存結果(其在這裏被剝削作爲一個關聯數組)。但是,如果節點對象中沒有選擇器的結果,那麼它將查詢DOM。此外還有一個額外的參數來強制更新nodes中的選擇器。

另外,您可以使用lodash的memoize功能,像這樣:

// inside your Module 
$: _.memoize(jQuery); 
+0

哇。這是一個非常酷的想法。 – 2013-02-27 19:31:36