简体   繁体   中英

Global variable unavailable within function?

在此处输入图片说明

I'm working on reproducing a live filter box with handsontable based on the built in search functionality at http://docs.handsontable.com/0.15.0-beta6/demo-search-for-values.html .

Right Now I'm working with the simplest use case ( http://jsfiddle.net/kc11/uL3L4teL/ ) from the docs.

As explained in the docs, In this code if you enter a search string, you get the matching cells outputted to the console using the following function:

         Handsontable.Dom.addEvent(searchFiled, 'keyup', function (event) {
                var queryResult = hot.search.query(this.value);

                console.log(queryResult);
                hot.render();

I want to grab the rows in the data array that match the search string and filter the original data 'data' by the search string before redisplaying the table. This partially works using:

 Handsontable.Dom.addEvent(searchFiled, 'keyup', function (event) {
    var queryResult = hot.search.query(this.value);

    console.log(queryResult);
    rows = getRowsFromObjects(queryResult);
    console.log('hot', hot.getData());
    console.log('data', data);
    var data = hot.getData();
    var filtered = data.filter(function(d, ix) { return rows.indexOf(ix) >= 0; });
    console.log('filtered', filtered);

    hot.loadData(filtered);


});

As you can see in http://jsfiddle.net/uL3L4teL/2/ , but I need to replace

var data = hot.getData();

(a handsontable function which gets the current data in the table) with the global 'data' (defined at the top) for the searching to work. But the global data is undefined in the function. How can I fix this?

If the "global" data variable that you are referring to "at the top" is this one

var
data = [
  ['Nissan', 2012, 'black', 'black'],
  ['Nissan', 2013, 'blue', 'blue'],
  ['Chrysler', 2014, 'yellow', 'black'],
  ['Volvo', 2015, 'yellow', 'gray']
]

then that is not global. That variable is local to the DOMContentLoaded event handler function. I presume even though you declare the other event handlers within that same block, they are being called with a different scope, making that variable unavailable. As was suggested in a comment, you can assign it to a global variable like window, or just declare it in a global scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM