Reputation:
I'm trying to sort an array of list elements in IE8 like this:
function comparator(params) {
var keepSelectedOnTop = params.keepSelectedOnTop;
return function (a, b) { // a, b are DOM objects
a = $(a); // wrap with jQuery
b = $(b);
if (keepSelectedOnTop) {
if (a.is(".selected") && !b.is(".selected")) {
return -1;
} else if (!a.is(".selected") && b.is(".selected")) {
return 1;
}
}
return a.text().localeCompare(b.text());
}
}
// ...
var items = $("ul li").detach().toArray();
items.sort(comparator(params));
This works for small lists, but when I have many elements I get an undefined is null or not an object
error. When I break on the exception with the debugger b
is undefined
after the assignment.
Did anyone encounter this before? It works fine in other browsers and it seems perfectly valid JS.
P.S. the jQuery version is 1.7.2
Upvotes: 0
Views: 369
Reputation:
After several trial & error attempts it seems that changing the assignments in the comparator solves the issue, but it doesn't make sense:
function comparator(params) {
var keepSelectedOnTop = params.keepSelectedOnTop;
return function (aDom, bDom) {
var a = $(aDom), b = $(bDom); // Use different vars for the wrappers
if (keepSelectedOnTop) {
if (a.is(".selected") && !b.is(".selected")) {
return -1;
} else if (!a.is(".selected") && b.is(".selected")) {
return 1;
}
}
return a.text().localeCompare(b.text());
}
}
For some reason the above works, but the initial version where I reassigned different values to the parameters doesn't.
Upvotes: 0
Reputation: 1573
Why sort?
var items = $("ul li")
items = [].concat(items.filter(".selected").toArray()
,items.filter(":not(.selected)").toArray())
Upvotes: 1