1

哪些模式可用于在大型 JavaScript 应用程序中缓存许多 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
    });
  }

};

那里一定有一个更干净的速记。

4

1 回答 1

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 () { /* ... */ });
  }
};

So with this every time you query for a selector using the locally-scoped Module.$ function it would cache the result in the nodes object (which here is being exploited as an associative array). However if there was no result for that selector in the nodes object then it would query the DOM for it. Furthermore there's an added param to force the selectors in nodes to be updated.

Alternatively you could use lodash's memoize function, like so:

// inside your Module
$: _.memoize(jQuery);
于 2013-02-27T16:40:46.993 回答