From fcb24c37404cf0bc1a0ac99a7c7b479e72f04df6 Mon Sep 17 00:00:00 2001 From: Bartek Fabiszewski Date: Mon, 16 Dec 2019 18:25:10 +0100 Subject: [PATCH] unobserveAll: remove observers from all properties if property argument is missing --- js/src/observe.js | 14 ++++++++++---- js/test/observe.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/js/src/observe.js b/js/src/observe.js index 25cdea2..d0e2744 100644 --- a/js/src/observe.js +++ b/js/src/observe.js @@ -205,13 +205,19 @@ export default class uObserve { /** * Remove all observers from object's property or all it's properties - * unobserve(obj, prop) removes all observes from given property prop; - * unobserve(obj) removes all observers from all properties of object obj. + * unobserveAll(obj, prop) removes all observes from given property prop; + * unobserveAll(obj) removes all observers from all properties of object obj. * @param {Object} obj - * @param {string} property + * @param {string=} property */ static unobserveAll(obj, property) { - if (this.isObserved(obj, property)) { + if (arguments.length === 1) { + for (const prop in obj) { + if (obj.hasOwnProperty(prop)) { + this.unobserveAll(obj, prop); + } + } + } else if (this.isObserved(obj, property)) { console.log(`Removing all observers for ${property}…`); if (Array.isArray(obj[property])) { this.restoreArrayPrototypes(obj[property]); diff --git a/js/test/observe.test.js b/js/test/observe.test.js index 97ed7c4..239fc8d 100644 --- a/js/test/observe.test.js +++ b/js/test/observe.test.js @@ -438,6 +438,38 @@ describe('Observe tests', () => { expect(object.arr).toEqual([ 1, 2, 3 ]); }); + it('should remove all observers of all object properties', () => { + // given + let result2 = false; + let resultValue2; + const observer = (value) => { + result = true; + resultValue = value; + }; + const observer2 = (value) => { + result2 = true; + resultValue2 = value; + }; + object.observed2 = null; + uObserve.observe(object, 'observed', observer); + uObserve.observe(object, 'observed2', observer2); + // when + uObserve.unobserveAll(object); + + expect(result).toBe(false); + expect(result2).toBe(false); + object.observed = 2; + object.observed2 = 2; + // then + expect(result).toBe(false); + expect(resultValue).toBe(undefined);// eslint-disable-line no-undefined + expect(result2).toBe(false); + // noinspection JSUnusedAssignment + expect(resultValue2).toBe(undefined);// eslint-disable-line no-undefined + expect(object.observed).toBe(2); + expect(object.observed2).toBe(2); + }); + it('should throw error when observing non-existing property', () => { // given const nonExisting = '___non-existing___';