Skip to content

Commit a8f5185

Browse files
author
Jake Harding
committed
Cancel pending updates when dropdown is cleared. Closes twitter#702.
1 parent 64bf4c6 commit a8f5185

2 files changed

Lines changed: 35 additions & 4 deletions

File tree

‎src/typeahead/dataset.js‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,24 @@ var Dataset = (function() {
141141
var that = this;
142142

143143
this.query = query;
144-
this.source(query, renderIfQueryIsSame);
145-
146-
function renderIfQueryIsSame(suggestions) {
147-
query === that.query && that._render(query, suggestions);
144+
this.canceled = false;
145+
this.source(query, render);
146+
147+
function render(suggestions) {
148+
// if the update has been canceled or if the query has changed
149+
// do not render the suggestions as they've become outdated
150+
if (!that.canceled && query === that.query) {
151+
that._render(query, suggestions);
152+
}
148153
}
149154
},
150155

156+
cancel: function cancel() {
157+
this.canceled = true;
158+
},
159+
151160
clear: function clear() {
161+
this.cancel();
152162
this._render(this.query || '');
153163
},
154164

‎test/dataset_view_spec.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,16 @@ describe('Dataset', function() {
128128
});
129129
});
130130

131+
it('should not render suggestions if update was canceled', function() {
132+
this.source.andCallFake(fakeGetWithAsyncResults);
133+
this.dataset.update('woah');
134+
this.dataset.cancel();
135+
136+
waits(100);
137+
138+
runs(function() { expect(this.dataset.getRoot()).toBeEmpty(); });
139+
});
140+
131141
it('should trigger rendered after suggestions are rendered', function() {
132142
var spy;
133143

@@ -148,6 +158,17 @@ describe('Dataset', function() {
148158
this.dataset.clear();
149159
expect(this.dataset.getRoot()).toBeEmpty();
150160
});
161+
162+
it('should cancel pending updates', function() {
163+
var spy = spyOn(this.dataset, 'cancel');
164+
165+
this.source.andCallFake(fakeGetWithSyncResults);
166+
this.dataset.update('woah');
167+
expect(this.dataset.canceled).toBe(false);
168+
169+
this.dataset.clear();
170+
expect(spy).toHaveBeenCalled();
171+
});
151172
});
152173

153174
describe('#isEmpty', function() {

0 commit comments

Comments
 (0)