Attribute model with get, set, unset, and change listeners
A listing editor keeps the listing being edited in one model object. The price field, the preview card, and the “unsaved changes” badge all listen to that model, and each one only cares about some attributes. Implement a class AttributeModel that stores attributes and notifies listeners when they change.
const model = new AttributeModel(initialAttributes?);
model.get(key) // the value, or undefined
model.has(key) // => boolean
model.set(key, value) // => model
model.set({ key: value }) // => model, several attributes at once
model.unset(key) // => model
model.previous(key) // value before the latest change (see below)
model.toJSON() // => a plain object copy of all attributes
model.on(event, handler) // => unsubscribe function
model.once(event, handler) // => unsubscribe function, handler runs at most once
initialAttributes (a plain object, optional). It never mutates it and fires no events.'constructor' or 'toString'.undefined does not exist: set(key, undefined) behaves like unset(key), and has(key) is false. null is an ordinary value.Object.is, so setting NaN over NaN changes nothing, while -0 over 0 is a change.toJSON() returns a new object each time. Changing it does not affect the model.set or unset call actually changes, fire 'change:<key>' with (newValue, previousValue, model). For a removed attribute, newValue is undefined; for a new one, previousValue is undefined.'change' once with (changedKeys, model), where changedKeys is an array of the changed keys.set(object), keys are processed in Object.keys order, and both the per-key events and changedKeys follow that order.'change:a' handler already sees the new value of b.set or unset. That call stores its values and fires its own events immediately, before the remaining events of the outer call.previous(key)Returns the value key had right before the most recent set/unset call that changed at least one attribute. If that call did not touch key, this is the same as get(key). Before any change, it equals get(key).
const listing = new AttributeModel({ title: 'Loft', price: 120 });
listing.on('change:price', (price, oldPrice) => {
console.log(`price ${oldPrice} -> ${price}`);
});
listing.on('change', (keys) => console.log('changed', keys));
listing.set({ price: 140, guests: 4 });
// logs: price 120 -> 140
// logs: changed ['price', 'guests']
listing.set('price', 140); // nothing changed, nothing logged
listing.previous('price'); // => 120
listing.unset('guests'); // logs: changed ['guests']
listing.has('guests'); // => false
listing.toJSON(); // => { title: 'Loft', price: 140 }