Skip to content

Commit 7187bc7

Browse files
bradvogelhswolff
authored andcommitted
feat: Fix bug where models were not listened to when they were set as properties, after initial construction.
1 parent e3eee55 commit 7187bc7

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

lib/connect-backbone-to-react.js

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,13 @@ module.exports = function connectBackboneToReact(
9090
createEventListeners() {
9191
Object.keys(this.models).forEach(mapKey => {
9292
const model = this.models[mapKey];
93+
this.createEventListener(mapKey, model);
94+
});
95+
}
9396

94-
getEventNames(mapKey).forEach(name => {
95-
model.on(name, this.createNewProps, this);
96-
});
97+
createEventListener(modelName, model) {
98+
getEventNames(modelName).forEach(name => {
99+
model.on(name, this.createNewProps, this);
97100
});
98101
}
99102

@@ -112,6 +115,17 @@ module.exports = function connectBackboneToReact(
112115
componentWillReceiveProps(nextProps, nextContext) {
113116
this.setModels(nextProps, nextContext);
114117
this.createNewProps();
118+
119+
// Bind event listeners for each model that changed.
120+
Object.keys(this.models).forEach(mapKey => {
121+
const model = this.models[mapKey];
122+
if (this.props.models[mapKey] === this.models[mapKey] ||
123+
(this.context.models && this.context.models[mapKey] === this.models[mapKey])) {
124+
return; // Did not change.
125+
}
126+
127+
this.createEventListener(mapKey, model);
128+
});
115129
}
116130

117131
componentWillUnmount() {

test/connect-backbone-to-react.test.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,7 @@ describe('connectBackboneToReact', function() {
477477
let setStateSpy;
478478
let newName;
479479
let newAge;
480+
let newUserModel;
480481

481482
beforeEach(function() {
482483
const ConnectedTest = connectBackboneToReact(mapModelsToProps)(TestComponent);
@@ -488,7 +489,7 @@ describe('connectBackboneToReact', function() {
488489
newName = 'Robert';
489490
newAge = '30';
490491

491-
const newUserModel = new UserModel({
492+
newUserModel = new UserModel({
492493
name: newName,
493494
age: newAge,
494495
hungry: false,
@@ -514,6 +515,13 @@ describe('connectBackboneToReact', function() {
514515
assert.equal(stub.find('.age').text(), newAge);
515516
assert.equal(stub.find('.hungry').text(), 'not hungry');
516517
});
518+
519+
it('listen for updates', function() {
520+
newName = 'Bob';
521+
newUserModel.set('name', newName);
522+
523+
assert.equal(stub.find('.name').text(), newName);
524+
});
517525
});
518526

519527
describe('when unmounted in an event listener and subscribed to "all" event', function() {

0 commit comments

Comments
 (0)