From dfde7b48d6a2c80e8ef149da4134fac4327fe374 Mon Sep 17 00:00:00 2001 From: Christian Haas Date: Fri, 6 Sep 2013 20:50:57 +0200 Subject: [PATCH] Ensuring context set for delayed callbacks - also, fixing standalone test runner --- spec/SubscriptionDefinition.spec.js | 22 ++++++++++++++++++++++ spec/index.html | 10 +++++----- src/SubscriptionDefinition.js | 6 ++++-- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/spec/SubscriptionDefinition.spec.js b/spec/SubscriptionDefinition.spec.js index 35d58d5..bbb1d21 100644 --- a/spec/SubscriptionDefinition.spec.js +++ b/spec/SubscriptionDefinition.spec.js @@ -119,6 +119,17 @@ describe( "SubscriptionDefinition", function () { sDefe.callback( "second", { topic : "TestTopic" } ); results.push( "first" ); } ); + + it( "Should keep the context intact", function ( done ) { + var context = { + key: 1234 + }; + sDefe = new SubscriptionDefinition( "TestChannel", "TestTopic", function ( data, env ) { + expect( this ).to.be( context ); + done(); + } ).withContext(context).defer(); + sDefe.callback( "stuff", { topic : "TestTopic" } ); + } ); } ); describe( "When delaying the callback", function () { @@ -135,6 +146,17 @@ describe( "SubscriptionDefinition", function () { sDefe.callback( "second", { topic : "TestTopic" } ); results.push( "first" ); } ); + + it( "Should keep the context intact", function ( done ) { + var context = { + key: 1234 + }; + sDefe = new SubscriptionDefinition( "TestChannel", "TestTopic", function ( data, env ) { + expect( this ).to.be( context ); + done(); + } ).withContext(context).withDelay( 200 ); + sDefe.callback( "stuff", { topic : "TestTopic" } ); + } ); } ); describe( "When debouncing the callback", function () { diff --git a/spec/index.html b/spec/index.html index dbd73fb..4d74a45 100644 --- a/spec/index.html +++ b/spec/index.html @@ -1,14 +1,14 @@ - +
- - - - + + + + diff --git a/src/SubscriptionDefinition.js b/src/SubscriptionDefinition.js index c4d4c69..ddb78f8 100644 --- a/src/SubscriptionDefinition.js +++ b/src/SubscriptionDefinition.js @@ -37,9 +37,10 @@ SubscriptionDefinition.prototype = { defer : function () { var fn = this.callback; + var context = this.context; this.callback = function ( data, env ) { setTimeout( function () { - fn( data, env ); + fn.call( context, data, env ); }, 0 ); }; return this; @@ -113,9 +114,10 @@ SubscriptionDefinition.prototype = { throw "Milliseconds must be a number"; } var fn = this.callback; + var context = this.context; this.callback = function ( data, env ) { setTimeout( function () { - fn( data, env ); + fn.call( context, data, env ); }, milliseconds ); }; return this;