openmct/src/api/objects/MutableDomainObject.js
Andrew Henry 92737b43af
[API] Changes to mutation API (#3483)
Changes how object mutation works behind the scenes in order to keep objects in sync automatically when their model changes.

* The way that objects are mutated and observed has not changed, openmct.objects.mutate and openmct.objects.observe should still be used in the same way that they were before.

* Behind the scenes, domain objects that are mutable are wrapped in a new MutableDomainObject that exposes mutator and observer functions that allow objects to be mutated in such a way that all instances can be kept in sync.

* It is now possible to retrieve MutableDomainObjects from the API, instead of regular domain objects. These are automatically updated when mutation occurs on any instance of the object, replacing the need for "*" listeners. Note that the view API now provides objects in this form by default. Therefore, you do not need to do anything differently in views, the domain objects will just magically keep themselves up to date.

* If for some reason you need to retrieve an object manually via openmct.objects.get (you should ask why you need to do this) and you want it to magically keep itself in sync, there is a new API function named openmct.objects.getMutable(identifier). Note that if you do this you will be responsible for the object's lifecycle. It relies on listeners which must be destroyed when the object is no longer needed, otherwise memory leaks will occur. You can destroy a MutableDomainObject and its (internal) listeners by calling openmct.objects.destroyMutable(mutableDomainObject). Any listeners created by calls to openmct.objects.observe need to be cleaned up separately.

* If the composition of a MutableDomainObject is retrieved using the Composition API, all children will be returned as MutableDomainObjects automatically. Their lifecycle will be managed automatically, and is tied to the lifecycle of the parent.
Any MutableDomainObject provided by the Open MCT framework itself (eg. provided to view providers by the View API, or from the composition API) will have its lifecycle managed by Open MCT, you don't need to worry destroying it.
2021-01-17 14:15:09 -08:00

138 lines
5.5 KiB
JavaScript

/*****************************************************************************
* Open MCT, Copyright (c) 2014-2020, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* Open MCT is licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* Open MCT includes source code licensed under additional open source
* licenses. See the Open Source Licenses file (LICENSES.md) included with
* this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information.
*****************************************************************************/
import _ from 'lodash';
import utils from './object-utils.js';
import EventEmitter from 'EventEmitter';
const ANY_OBJECT_EVENT = 'mutation';
/**
* Wraps a domain object to keep its model synchronized with other instances of the same object.
*
* Creating a MutableDomainObject will automatically register listeners to keep its model in sync. As such, developers
* should be careful to destroy MutableDomainObject in order to avoid memory leaks.
*
* All Open MCT API functions that provide objects will provide MutableDomainObjects where possible, except
* `openmct.objects.get()`, and will manage that object's lifecycle for you. Calling `openmct.objects.getMutable()`
* will result in the creation of a new MutableDomainObject and you will be responsible for destroying it
* (via openmct.objects.destroy) when you're done with it.
*
* @typedef MutableDomainObject
* @memberof module:openmct
*/
class MutableDomainObject {
constructor(eventEmitter) {
Object.defineProperties(this, {
_globalEventEmitter: {
value: eventEmitter,
// Property should not be serialized
enumerable: false
},
_instanceEventEmitter: {
value: new EventEmitter(),
// Property should not be serialized
enumerable: false
},
_observers: {
value: [],
// Property should not be serialized
enumerable: false
},
isMutable: {
value: true,
// Property should not be serialized
enumerable: false
}
});
}
$observe(path, callback) {
let fullPath = qualifiedEventName(this, path);
let eventOff =
this._globalEventEmitter.off.bind(this._globalEventEmitter, fullPath, callback);
this._globalEventEmitter.on(fullPath, callback);
this._observers.push(eventOff);
return eventOff;
}
$set(path, value) {
_.set(this, path, value);
_.set(this, 'modified', Date.now());
//Emit secret synchronization event first, so that all objects are in sync before subsequent events fired.
this._globalEventEmitter.emit(qualifiedEventName(this, '$_synchronize_model'), this);
//Emit a general "any object" event
this._globalEventEmitter.emit(ANY_OBJECT_EVENT, this);
//Emit wildcard event, with path so that callback knows what changed
this._globalEventEmitter.emit(qualifiedEventName(this, '*'), this, path, value);
//Emit events specific to properties affected
let parentPropertiesList = path.split('.');
for (let index = parentPropertiesList.length; index > 0; index--) {
let parentPropertyPath = parentPropertiesList.slice(0, index).join('.');
this._globalEventEmitter.emit(qualifiedEventName(this, parentPropertyPath), _.get(this, parentPropertyPath));
}
//TODO: Emit events for listeners of child properties when parent changes.
// Do it at observer time - also register observers for parent attribute path.
}
$on(event, callback) {
this._instanceEventEmitter.on(event, callback);
return () => this._instanceEventEmitter.off(event, callback);
}
$destroy() {
this._observers.forEach(observer => observer());
delete this._globalEventEmitter;
delete this._observers;
this._instanceEventEmitter.emit('$_destroy');
}
static createMutable(object, mutationTopic) {
let mutable = Object.create(new MutableDomainObject(mutationTopic));
Object.assign(mutable, object);
mutable.$observe('$_synchronize_model', (updatedObject) => {
let clone = JSON.parse(JSON.stringify(updatedObject));
let deleted = _.difference(Object.keys(mutable), Object.keys(updatedObject));
deleted.forEach((propertyName) => delete mutable[propertyName]);
Object.assign(mutable, clone);
});
return mutable;
}
static mutateObject(object, path, value) {
_.set(object, path, value);
_.set(object, 'modified', Date.now());
}
}
function qualifiedEventName(object, eventName) {
let keystring = utils.makeKeyString(object.identifier);
return [keystring, eventName].join(':');
}
export default MutableDomainObject;