MENU
Extracting Data From Backbone Models
Below, we use a custom hook to extract all attributes of a Backbone model into state. We subscribe to the model's 'change' event inside a useEffect (and unsubscribe on cleanup). When the event fires, we update the state with the model's current attributes. Because the effect's dependency array includes the model itself, if the model prop changes to a different instance, React automatically unsubscribes from the old model and subscribes to the new one before resyncing state.
import React, { useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import Backbone from 'backbone';
function useBackboneModel(model) {
const [attributes, setAttributes] = useState(() => ({ ...model.attributes }));
useEffect(() => {
setAttributes({ ...model.attributes });
function handleChange(changedModel) {
setAttributes({ ...changedModel.attributes });
}
model.on('change', handleChange);
return () => model.off('change', handleChange);
}, [model]);
return attributes;
}
function NameInput(props) {
return (
<p>
<input value={props.firstName} onChange={props.handleChange} /><br />
My name is {props.firstName}.
</p>
);
}
function Example({ model }) {
const attributes = useBackboneModel(model);
function handleChange(e) {
model.set('firstName', e.target.value);
}
return <NameInput {...attributes} handleChange={handleChange} />;
}
const model = new Backbone.Model({ firstName: 'Frodo' });
const root = createRoot(document.getElementById('root'));
root.render(<Example model={model} />);