Isotope Dynamic Sorts

末鹿安然 提交于 2019-12-05 07:26:29

问题


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());
  }
}


来源:https://stackoverflow.com/questions/12919827/isotope-dynamic-sorts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!