Problem
Before modern UI libraries, Backbone.js helped structure web apps with models, views, and collections. Implement a subset of BackboneModel that stores attributes and fires events when specific attributes change.
API
new BackboneModel([initialValues])
Creates a model instance. Optional initialValues is an object of attribute/value pairs. Attributes and listeners are isolated per instance — callbacks must not react to changes on other models.
const person1 = new BackboneModel();
const person2 = new BackboneModel({ name: "John", age: 32 });
model.get(attribute)
Returns the value of attribute, or undefined if not set.
model.set(attribute, value)
Sets an attribute and fires the "change" event for that attribute.
model.has(attribute)
Returns true if the attribute exists on the model, else false.
model.unset(attribute)
Removes the attribute and fires the "unset" event for that attribute.
model.on(event, attribute, callback, context?)
Registers a listener for a specific attribute. event is "change" or "unset".
context (optional) is the this value when invoking callback.
Example
const user = new BackboneModel({ name: "Ada", score: 10 });
user.on("change", "name", (attr, next, prev) => {
console.log(`${attr}: ${prev} → ${next}`);
});
user.on("unset", "score", (attr) => {
console.log(`removed ${attr}`);
});
user.set("name", "Grace");
user.unset("score");
console.log(user.has("score"));
console.log(user.get("name"));