unobserveAll: remove observers from all properties if property argument is missing

This commit is contained in:
Bartek Fabiszewski 2019-12-16 18:25:10 +01:00
parent 8260b7ab6c
commit fcb24c3740
2 changed files with 42 additions and 4 deletions

View File

@ -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]);

View File

@ -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___';