Skip to content

Commit

Permalink
Change multiselect cache structure
Browse files Browse the repository at this point in the history
The exisiting structure used an Object as a cache where the keys are the
values of option elements, and values are the HTML content of the option
elements. In Javascript, if a numeric value in the form of a string is
assigned as a key, it gets converted to an integer. Optimization
routines would then order the object to ensure faster access to
elements. For example:

cache = {}
cache['2'] = "two"
cache['1'] = "one"
console.log(cache[2])  #=> "two"
console.log(cache[1])  #=> "one"
console.log(cache)     #=> {1: "one", 2: "two"}

Note the coercion of strings to ints above. This messes with the
ordering of multiselect options list whenever there is a user input. To
avoid this from happening, the keys need to have a string that can't be
coerced automatically, and then preserve the value of the option
element.

I chose to use an object that stores the option value and the option
HTML as the value of the cache and a string of the format 'o_<option
value>' as the key. This ensures that the insertion order is preserved.
This is the new structure:

cache = {
  'o_271': { id: 271, value: 'CartItem railsadminteam#271'},
  'o_270': { id: 270, value: 'CartItem railsadminteam#270}'
}
  • Loading branch information
meghaarora42 committed Sep 28, 2015
1 parent 2366ea4 commit 216adc8
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions app/assets/javascripts/rails_admin/ra.filtering-multiselect.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,10 @@

this.element.find("option").each(function(i, option) {
if (option.selected) {
widget._cache[option.value] = option.innerHTML;
widget._cache['o_' + option.value] = {id: option.value, value: option.innerHTML};
$(option).clone().appendTo(widget.selection).attr("selected", false).attr("title", $(option).text());
} else {
widget._cache[option.value] = option.innerHTML;
widget._cache['o_' + option.value] = {id: option.value, value: option.innerHTML};
$(option).clone().appendTo(widget.collection).attr("selected", false).attr("title", $(option).text());
}
});
Expand All @@ -206,7 +206,8 @@
if (!this.options.xhr) {
for (i in this._cache) {
if (this._cache.hasOwnProperty(i)) {
matches.push({id: i, label: this._cache[i]});
option = this._cache[i];
matches.push({id: option.id, label: option.value});
}
}
}
Expand All @@ -231,8 +232,9 @@
query = new RegExp(query + '.*', 'i');

for (i in this._cache) {
if (this._cache.hasOwnProperty(i) && query.test(this._cache[i])) {
matches.push({id: i, label: this._cache[i]});
if (this._cache.hasOwnProperty(i) && query.test(this._cache[i]['value'])) {
option = this._cache[i];
matches.push({id: option.id, label: option.value});
}
}

Expand Down

0 comments on commit 216adc8

Please sign in to comment.