jqueryfilterjquery-datajquery-filter

jQuery filter by data property


I've the following snippet, which must return objects by some condition, but I got this error: Uncaught TypeError: Cannot read property 'obj1' of undefined. However, I see this data attr in the li object using console.

for(var i = 0; i < 15; i++){

  li = $('<li>List</li>');
  $(li).data('test', {obj1: (i < 10 ? 'some' : 'any')});
  $(li).appendTo('#list');
}

var f = $('#list li').filter(() => {
  return $(this).data('test').obj1 == 'any'
});

console.log($(f));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id ="list">

</ul>


Solution

  • The basic rule of thumb is to not to use arrow function when handling UI related stuffs. Like, as an event handler etc. Because the arrow function would bind its execution context to itself. And it cannot be overridden by any means.

    var f = $('#list li').filter(function() {
      return $(this).data('test').obj1 == 'any'
    });
    

    Use normal anonymous function instead of an arrow function. If you still want to use the arrow function, then the this would point to its execution context. It would point to window object in the executor of SO.