diff --git a/lib/index.js b/lib/index.js index 7f1275d19..b176d07b3 100644 --- a/lib/index.js +++ b/lib/index.js @@ -343,7 +343,7 @@ module.exports.render = function(options, cb) { bridge.success(data); } - var result = tryCallback(cb.callback, args.concat(done)); + var result = tryCallback(cb.callback.bind(options.context), args.concat(done)); if (result) { done(result); @@ -400,7 +400,7 @@ module.exports.renderSync = function(options) { var cb = normalizeFunctionSignature(signature, functions[signature]); options.functions[cb.signature] = function() { - return tryCallback(cb.callback, arguments); + return tryCallback(cb.callback.bind(options.context), arguments); }; }); } diff --git a/test/api.js b/test/api.js index 0ce4d4d77..6fa3e2ec2 100644 --- a/test/api.js +++ b/test/api.js @@ -911,6 +911,28 @@ describe('api', function() { }); }); + it('should call custom functions with correct context', function(done) { + function assertExpected(result) { + assert.equal(result.css.toString().trim(), 'div {\n foo1: 1;\n foo2: 2; }'); + } + var options = { + data: 'div { foo1: foo(); foo2: foo(); }', + functions: { + // foo() is stateful and will persist an incrementing counter + 'foo()': function() { + assert(this); + this.fooCounter = (this.fooCounter || 0) + 1; + return new sass.types.Number(this.fooCounter); + } + } + }; + + sass.render(options, function(error, result) { + assertExpected(result); + done(); + }); + }); + describe('should properly bubble up errors from sass color constructor', function() { it('four booleans', function(done) { sass.render({ @@ -1646,6 +1668,25 @@ describe('api', function() { done(); }); + + it('should call custom functions with correct context', function(done) { + function assertExpected(result) { + assert.equal(result.css.toString().trim(), 'div {\n foo1: 1;\n foo2: 2; }'); + } + var options = { + data: 'div { foo1: foo(); foo2: foo(); }', + functions: { + // foo() is stateful and will persist an incrementing counter + 'foo()': function() { + assert(this); + this.fooCounter = (this.fooCounter || 0) + 1; + return new sass.types.Number(this.fooCounter); + } + } + }; + assertExpected(sass.renderSync(options)); + done(); + }); }); describe('.renderSync({stats: {}})', function() {