Skip to content

Commit

Permalink
Improved the way the Lawnchair constructor ensures it was called with…
Browse files Browse the repository at this point in the history
… new.
  • Loading branch information
jaredatron committed Nov 26, 2011
1 parent 11577d8 commit 4503edd
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions src/Lawnchair.js
Expand Up @@ -4,33 +4,31 @@
* clientside json store
*
*/
var Lawnchair = function () {
var Lawnchair = function (options, callback) {
// ensure Lawnchair was called as a constructor
if (!(this instanceof Lawnchair)) return new Lawnchair(options, callback);

// lawnchair requires json
if (!JSON) throw 'JSON unavailable! Include http://www.json.org/json2.js to fix.'
// options are optional; callback is not
if (arguments.length <= 2 && arguments.length > 0) {
var callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1]
, options = (typeof arguments[0] === 'function') ? {} : arguments[0]
callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1];
options = (typeof arguments[0] === 'function') ? {} : arguments[0];
} else {
throw 'Incorrect # of ctor args!'
}
// TODO perhaps allow for pub/sub instead?
if (typeof callback !== 'function') throw 'No callback was provided';

// ensure we init with this set to the Lawnchair prototype
var self = (!(this instanceof Lawnchair))
? new Lawnchair(options, callback)
: this

// default configuration
self.record = options.record || 'record' // default for records
self.name = options.name || 'records' // default name for underlying store
this.record = options.record || 'record' // default for records
this.name = options.name || 'records' // default name for underlying store

// mixin first valid adapter
var adapter
// if the adapter is passed in we try to load that only
if (options.adapter) {
adapter = Lawnchair.adapters[self.indexOf(Lawnchair.adapters, options.adapter)]
adapter = Lawnchair.adapters[this.indexOf(Lawnchair.adapters, options.adapter)]
adapter = adapter.valid() ? adapter : undefined
// otherwise find the first valid adapter for this env
}
Expand All @@ -46,17 +44,14 @@ var Lawnchair = function () {

// yay! mixin the adapter
for (var j in adapter)
self[j] = adapter[j]
this[j] = adapter[j]

// call init for each mixed in plugin
for (var i = 0, l = Lawnchair.plugins.length; i < l; i++)
Lawnchair.plugins[i].call(self)
Lawnchair.plugins[i].call(this)

// init the adapter
self.init(options, callback)

// called as a function or as a ctor with new always return an instance
return self
this.init(options, callback)
}

Lawnchair.adapters = []
Expand Down

0 comments on commit 4503edd

Please sign in to comment.