From 4c4a2f220e8b233da564b0f243c31c5d64069390 Mon Sep 17 00:00:00 2001 From: Wojciech Zawistowski Date: Sun, 20 Oct 2013 10:38:26 +0200 Subject: [PATCH] refactors Discourse.debouncePromise --- .../discourse/components/debounce.js | 23 ++++++++----------- .../components/debounce_promise_test.js | 7 ++++-- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/app/assets/javascripts/discourse/components/debounce.js b/app/assets/javascripts/discourse/components/debounce.js index b9be435c6..7ffd329ac 100644 --- a/app/assets/javascripts/discourse/components/debounce.js +++ b/app/assets/javascripts/discourse/components/debounce.js @@ -47,25 +47,20 @@ Discourse.debounce = function(func, wait) { @param {Number} wait how long to wait **/ Discourse.debouncePromise = function(func, wait) { - var timeout = null; - var args = null; - var context = null; + var self, args, promise; + var later = function() { + func.apply(self, args).then(function (funcResult) { + promise.resolve(funcResult); + }); + }; return function() { - context = this; - var promise = Ember.Deferred.create(); + self = this; args = arguments; + promise = Ember.Deferred.create(); - if (!timeout) { - timeout = Em.run.later(function () { - timeout = null; - func.apply(context, args).then(function (y) { - promise.resolve(y); - }); - }, wait); - } + Ember.run.debounce(null, later, wait); return promise; }; }; - diff --git a/test/javascripts/components/debounce_promise_test.js b/test/javascripts/components/debounce_promise_test.js index 49822c5ce..2dac257bd 100644 --- a/test/javascripts/components/debounce_promise_test.js +++ b/test/javascripts/components/debounce_promise_test.js @@ -49,14 +49,17 @@ test("executes only once, no matter how many times debounced function is called originalAndCallbackFiredOnce("(second call was supressed)"); }); -test("does not prolong the timeout when the debounced function is called for the second time during the timeout", function() { +test("prolongs the timeout when the debounced function is called for the second time during the timeout", function() { debounced().then(callback); clock.tick(50); debounced().then(callback); clock.tick(50); - originalAndCallbackFiredOnce("exactly at the end of the original timeout"); + nothingFired("at the end of the original timeout"); + + clock.tick(50); + originalAndCallbackFiredOnce("exactly at the end of the prolonged timeout"); }); test("preserves last call's context and params when executing delayed function", function() {