Permalink
Browse files

Add loadAs for aliasing

  • Loading branch information...
1 parent 932b2f0 commit 93d6d7bbcd019e600bf62ec7fd1187695016188f @isaacs committed Jul 31, 2012
Showing with 35 additions and 8 deletions.
  1. +3 −2 README.md
  2. +21 −6 emcee.js
  3. +11 −0 test/basic.js
View
@@ -27,8 +27,11 @@ http.createServer(function (req, res) {
// check if the user is logged in.
var m = new MC()
+ // modelname, args...
m.load('login', req)
m.load('bike', req.url, res)
+ // different kind of bike: modelname, alias, args...
+ m.loadAs('bike', 'motorbike', 'dirt', 'roads')
m.end(function (er, models) {
// either there is an error, or all models are loaded on the
@@ -39,5 +42,3 @@ http.createServer(function (req, res) {
})
}).listen(1337)
```
-
-
View
@@ -19,22 +19,26 @@ MC.model = function (name, loader) {
return MC
}
-MC.prototype.load = function (name) {
+MC.prototype.loadAs = function (name, alias) {
if (!modelLoaders[name]) {
throw new Error('Unknown model: ' + name)
}
if (this.error) return
- var a = new Array(arguments.length)
- for (var i = 1; i < arguments.length; i ++) {
- a[i-1] = arguments[i]
+ if (!alias) alias = name
+
+ // [name, alias, args...] => [args..., cb]
+ var a = new Array(arguments.length - 1)
+ for (var i = 2; i < arguments.length; i ++) {
+ a[i - 2] = arguments[i]
}
- a[i-1] = next.bind(this)
+ a[i - 2] = next.bind(this)
+
this.loading ++
modelLoaders[name].apply(this, a)
function next (er, data) {
if (this.error) return
this.error = er
- this[name] = this.models[name] = data
+ this[alias] = this.models[alias] = data
this.loading --
if ((er || this.loading === 0) && this.ondone) {
@@ -43,6 +47,17 @@ MC.prototype.load = function (name) {
}
}
+MC.prototype.load = function (name) {
+ var a = new Array(arguments.length + 1)
+ a[0] = name
+ for (var i = 0; i < arguments.length; i ++) {
+ a[i+1] = arguments[i]
+ }
+ // a = [name, name, args...]
+
+ return this.loadAs.apply(this, a)
+}
+
MC.prototype.end = function (cb) {
this.ondone = cb
if (this.loading === 0 || this.error) {
View
@@ -50,3 +50,14 @@ tap.test('multiple', function (t) {
t.end()
})
})
+
+tap.test('aliasing', function (t) {
+ var m = new MC()
+ m.load('file', __filename)
+ m.loadAs('file', 'otherfile', __filename)
+ m.end(function (er, models) {
+ if (er) throw er
+ t.same(models.file, models.otherfile)
+ t.end()
+ })
+})

0 comments on commit 93d6d7b

Please sign in to comment.