From 03e891f10aa0b948d7f870ead47dbafc066fb61a Mon Sep 17 00:00:00 2001 From: Sam Gronblom Date: Fri, 15 Nov 2013 13:35:50 +0900 Subject: [PATCH 1/2] Require should so tests can be run using mocha --- test/resource.test.js | 1 + 1 file changed, 1 insertion(+) diff --git a/test/resource.test.js b/test/resource.test.js index ee22990..9b24f84 100644 --- a/test/resource.test.js +++ b/test/resource.test.js @@ -1,6 +1,7 @@ var assert = require('assert') , express = require('express') + , should = require('should') , Resource = require('..') , request = require('supertest') , batch = require('./support/batch'); From a30372bb130f920ffbc4cf9813bf2cad23c4ab0d Mon Sep 17 00:00:00 2001 From: Sam Gronblom Date: Fri, 15 Nov 2013 13:37:05 +0900 Subject: [PATCH 2/2] Bind handler if it is a function - This will be properly bound if it is used in the handler - Not supported for the case where the handler is an object which maps format name strings to handler functions --- index.js | 4 +++- test/resource.test.js | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 7789c21..91ea7bf 100644 --- a/index.js +++ b/index.js @@ -61,7 +61,9 @@ function Resource(name, actions, app) { // default actions for (var i = 0, key; i < orderedActions.length; ++i) { key = orderedActions[i]; - if (actions[key]) this.mapDefaultAction(key, actions[key]); + var handler = actions[key]; + if (typeof handler === 'function') handler = handler.bind(actions); + if (handler) this.mapDefaultAction(key, handler); } // auto-loader diff --git a/test/resource.test.js b/test/resource.test.js index 9b24f84..c64d009 100644 --- a/test/resource.test.js +++ b/test/resource.test.js @@ -56,6 +56,21 @@ describe('app.resource()', function(){ .expect('destroy forum 5', next()); }) + it('should bind this correctly', function(done) { + var app = express(); + var testController = { + 'users': 'userA userB', + 'index': function(req, res) { + res.send(this.users); + } + }; + + app.resource('users', testController); + request(app) + .get('/users') + .expect('userA userB', done); + }); + it('should support root resources', function(done){ var app = express(); var next = batch(done);