From d3a467d3664e5638fec82dfcee6bd13c82d9edb1 Mon Sep 17 00:00:00 2001 From: Adam Palay Date: Wed, 9 Mar 2016 17:04:33 -0500 Subject: [PATCH] Only add event listener if it hasn't been added yet --- .../spec/formula_equation_preview_spec.js | 21 +++++++++++++++++++ .../js/capa/src/formula_equation_preview.js | 14 ++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/common/static/js/capa/spec/formula_equation_preview_spec.js b/common/static/js/capa/spec/formula_equation_preview_spec.js index 11c2dd422d..4360d7513b 100644 --- a/common/static/js/capa/spec/formula_equation_preview_spec.js +++ b/common/static/js/capa/spec/formula_equation_preview_spec.js @@ -115,6 +115,27 @@ describe("Formula Equation Preview", function () { ]); }); + it('does not request again if the initial request has already been made', function () { + // jshint undef:false + expect(Problem.inputAjax.callCount).toEqual(1); + + // Reset the spy in order to check calls again. + Problem.inputAjax.reset(); + + // Enabling the formulaEquationPreview again to see if this will + // reinitialize input request once again. + formulaEquationPreview.enable(); + + // This part may be asynchronous, so wait. + waitsFor(function () { + return !Problem.inputAjax.wasCalled; + }, "times out in case of AJAX call", 1000); + + // Expect Problem.inputAjax was not called as input request was + // initialized before. + expect(Problem.inputAjax).not.toHaveBeenCalled(); + }); + it('makes a request on user input', function () { Problem.inputAjax.reset(); $('#input_THE_ID').val('user_input').trigger('input'); diff --git a/common/static/js/capa/src/formula_equation_preview.js b/common/static/js/capa/src/formula_equation_preview.js index b466a5854c..3e71b5954e 100644 --- a/common/static/js/capa/src/formula_equation_preview.js +++ b/common/static/js/capa/src/formula_equation_preview.js @@ -58,9 +58,17 @@ formulaEquationPreview.enable = function () { throttledRequest(inputData, this.value); }; - $this.on("input", initializeRequest); - // Ask for initial preview. - initializeRequest.call(this); + if (!$this.data("inputInitialized")) { + // Hack alert: since this javascript file is loaded every time a + // problem with mathjax preview is loaded, we wrap this step in this + // condition to make sure we don't attach multiple event listeners + // per math input if multiple such problems are loaded on a page. + $this.on("input", initializeRequest); + // Ask for initial preview. + initializeRequest.call(this); + // indicates that the initial preview is done for current $this! + $this.data("inputInitialized", true); + } } /**