Skip to content

Commit

Permalink
Prevent error when removing a model that does not match a view (#3472)
Browse files Browse the repository at this point in the history
Resolves #3445

If using `buildChildView` to build views that aren't given the collection's model, when the model is removed it would throw errors when other methods expected views to exist.
  • Loading branch information
paulfalgout authored and JSteunou committed Oct 2, 2017
1 parent dd2d562 commit 7699cee
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/next-collection-view.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,19 @@ const CollectionView = Backbone.View.extend({
},

_removeChildModels(models) {
return _.map(models, _.bind(this._removeChildModel, this));
return _.reduce(models, (views, model) => {
const removeView = this._removeChildModel(model);

if (removeView) { views.push(removeView); }

return views;
}, []);
},

_removeChildModel(model) {
const view = this.children.findByModel(model);

this._removeChild(view);
if (view) { this._removeChild(view); }

return view;
},
Expand Down
22 changes: 22 additions & 0 deletions test/unit/next-collection-view/collection-view-data.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,26 @@ describe('next CollectionView Data', function() {
expect(myCollectionView.$el.children()).to.have.lengthOf(2);
});
});

describe('when removing a model that does not match a children view model', function() {
let myCollectionView;
let collection;

beforeEach(function() {
collection = new Backbone.Collection([{ id: 1 }, { id: 2 }, { id: 3 }]);

const BuildCollectionView = MyCollectionView.extend({
buildChildView(child, ChildViewClass) {
return new ChildViewClass({ model: new Backbone.Model() });
}
});

myCollectionView = new BuildCollectionView({ collection });
myCollectionView.render();
});

it('should not throw an error', function() {
expect(collection.remove({ id: 1 })).to.not.throw;
});
});
});

0 comments on commit 7699cee

Please sign in to comment.