From 857fcfa31dd5d69da533217a5bfd4a702b2b5a2b Mon Sep 17 00:00:00 2001 From: Simon Kornblith Date: Wed, 14 Aug 2013 21:36:50 -0400 Subject: [PATCH] Add Zotero.lazy() and use in _getConnectionAsync I tried to describe what this function does earlier today and failed. Hopefully the code is clearer. --- chrome/content/zotero/xpcom/db.js | 15 +++------------ chrome/content/zotero/xpcom/zotero.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/chrome/content/zotero/xpcom/db.js b/chrome/content/zotero/xpcom/db.js index 666ac7e084..1fb40ef929 100644 --- a/chrome/content/zotero/xpcom/db.js +++ b/chrome/content/zotero/xpcom/db.js @@ -70,7 +70,6 @@ Zotero.DBConnection = function(dbName) { this._dbName = dbName; this._shutdown = false; this._connection = null; - this._connectionAsync = null; this._transactionDate = null; this._lastTransactionDate = null; this._transactionRollback = false; @@ -1021,23 +1020,15 @@ Zotero.DBConnection.prototype.asyncResult = function (val) { /** * Asynchronously return a connection object for the current DB */ -Zotero.DBConnection.prototype._getConnectionAsync = function () { - if (this._connectionAsync) { - return Q(this._connectionAsync); - } - +Zotero.DBConnection.prototype._getConnectionAsync = Zotero.lazy(function() { var db = this._getDBConnection(); var options = { path: db.databaseFile.path }; var self = this; Zotero.debug("Asynchronously opening DB connection"); - return Q(this.Sqlite.openConnection(options) - .then(function(conn) { - self._connectionAsync = conn; - return conn; - })); -}; + return Q(this.Sqlite.openConnection(options)); +}); /* diff --git a/chrome/content/zotero/xpcom/zotero.js b/chrome/content/zotero/xpcom/zotero.js index 06a00ddc51..aa80c47a52 100644 --- a/chrome/content/zotero/xpcom/zotero.js +++ b/chrome/content/zotero/xpcom/zotero.js @@ -1518,6 +1518,25 @@ Components.utils.import("resource://gre/modules/Services.jsm"); return; }; + /** + * Generate a function that produces a static output + * + * Zotero.lazy(fn) returns a function. The first time this function + * is called, it calls fn() and returns its output. Subsequent + * calls return the same output as the first without calling fn() + * again. + */ + this.lazy = function(fn) { + var x, called = false; + return function() { + if(!called) { + x = fn.apply(this); + called = true; + } + return x; + }; + }; + /** * Pumps a generator until it yields false. See itemTreeView.js for an example. *