Skip to curriculum
Jump to the editor

9.5. An observable model with change events

Medium
Topics

This question is in

9. Prototypes and classes
25–35 min

A profile form, a header avatar and a settings panel all show the same user. When the name changes in one place, the other two must redraw, and only when something really changed. An observable model keeps the values and tells registered listeners about each change, so views subscribe to the model instead of to each other.

Write the class Model in model.js. It stores named values, and every set call that changes something fires "change:<key>" events for each changed key and one "change" event for the whole call.

Signature

JAVASCRIPT
class Model {
  constructor(initial)    // initial: an object, optional
  get(key)                // the value, or undefined
  set(key, value)         // returns the model
  set(changes)            // changes: an object of keys and values; returns the model
  on(event, listener)     // returns a function that unregisters the listener
  toJSON()                // a new plain object of every key and value
}

Listeners are called as:

  • "change:<key>": listener(value, previous, model)
  • "change": listener(changes, model), where changes holds only the keys that changed, with their new values.

Requirements

  1. The model starts with a copy of initial's keys and values (empty without it); later changes to initial do not affect it. get returns undefined for a missing key.
  2. set(key, value) and set(changes) store the values and return the model.
  3. A key the model does not have yet has changed when it is set, whatever the value, undefined included: the key now exists, and toJSON lists it. A key the model already has has changed when Object.is(old value, new value) is false: setting the same value (or the same object) fires nothing, NaN to NaN is no change, 0 to -0 is a change.
  4. For each changed key, "change:<key>" listeners run with the new value, the old value and the model. A listener for one key never runs for another.
  5. After those, "change" listeners run once per set call, with an object of only the changed keys. A call that changes nothing fires no "change" at all.
  6. Events fire only after every value of the call is stored, in the order of the keys, with "change" last.
  7. on returns a function that unregisters that one registration; calling it again does nothing. The same function registered twice runs twice, and one unregister leaves the other.
  8. The listeners of an event are the ones registered when it started: a listener that unregisters itself does not make the next one get skipped, and a listener added during an event first runs on the next one.
  9. Each model has its own values and listeners.
  10. toJSON() returns a new plain object each time, so JSON.stringify(model) works and changing the copy does not change the model.
  11. Every string is an ordinary key, including "__proto__" and "toString".
  12. A set call made inside a listener stores its values and fires its own events.
  13. on throws a TypeError when the listener is not a function.

Examples

JAVASCRIPT
const user = new Model({ name: "Ana", age: 30 });
user.on("change:name", (value, previous) => console.log(previous, "->", value));
user.on("change", (changes) => console.log("changed", changes));

user.set("name", "Ben");
// "Ana -> Ben"
// "changed { name: 'Ben' }"

user.set({ name: "Ben", age: 31 });
// "changed { age: 31 }"   (name did not change, so no change:name)

user.set("age", 31);
// nothing: no change

user.set("nickname", undefined);
// "changed { nickname: undefined }"   (a new key is a change, even with the value undefined)
JAVASCRIPT
const off = user.on("change", () => console.log("saved"));
off();
user.set("age", 32);     // "changed { age: 32 }" only
JSON.stringify(user);    // '{"name":"Ben","age":32}'

Environment

  • Plain JavaScript in a browser page; the tests use the global class Model from model.js.
  • Events run synchronously, during the set call. What happens when a listener throws is not part of this problem.
  • Keys are strings. Nested objects are stored as they are; a change inside a stored object is not detected.

Hints

  1. If you loop over the listener array while a listener removes itself from it, which listener moves into the slot you just visited?
  2. How can on tell two registrations of the same function apart, so that one unregister removes only one of them?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…