Isotope Dynamic Sorts

2020-06-30 04:01发布

问题:

I'm using the jQuery Isotope plugin (http://isotope.metafizzy.co/) which is awesome, but I have a problem with creating the sorts. It's more of a JavaScript problem than anything to do with Isotope itself.

The problem is that I'm building the sort data dynamically. So I've created a function that makes the sortData. An example below:

function getSortData(){
    sortData = {};
    var sorts = ['symbol', 'number', 'score', 'name'];
    for (var i in sorts) {
      sortData[sorts[i]] = function($elem) {
        console.log(sorts[i]);
        return parseInt($elem.find('.'+ sorts[i]).text());     
      }
    }
    return sortData;
  }

So the problem is that the anonymous function inside always runs after the entire getSortData() function has run. Resulting in the last item in the sorts array being assigned to the sort[i] variable.

This is shown in this fiddle: http://jsfiddle.net/xzZR4/ You'll see that the 'name' item is always outputted to the console.

I can't think of another way to create the getSortData object that will allow the correct sort name to be passed.

Anyone with any ideas?

回答1:

Got it...

What was really needed was to allow the sort field name variable to have local scope inside the anonymous sort function. As I wasn't able to pass in the sort field directly into the anonymous function (as it's called by Isotope, so I can't control the parameters passed to it).

So the trick was to create another function that returned an anonymous function, this would take the field as an argument, making it have local scope.

function getSortData(){
    sortData = {};
    var sorts = ['symbol', 'number', 'score', 'name'];
    var sortField;
    for (var i in sorts) {
      sortField = sorts[i];
      sortData[sortField] = getSortDataCallback(sortField)
    }
    return sortData;
  }

function getSortDataCallback(sortField) {
  return function($elem) {
    return parseInt($elem.find('.'+ sortField).text());
  }
}