javascript-数组过滤器完成时分配变量

我试图把进度微调器放在数据加载上。用户单击html按钮,然后执行以下功能。阵列过滤器可能需要一些时间,具体取决于阵列大小。我希望变量isLoading在开始时为true,在过滤器功能完成时为false。变量isLoading用于显示/隐藏进度微调器。

myfunction(val){
    this.isLoading = true   
    var data =  this.myarray.filter(function(item) { 
      // this.isLoading = false // tried this, throws error - Cannot set property 'isLoading' of undefined     
      return item.name == val;      
    });
    this.showdata = data[0]
    // this.isLoading = false // tried this, but this does not show effect
}

请提出建议,如何处理。 谢谢

评论
舒灵波
舒灵波

This is happening because functions in JavaScript has their own context, meaning this inside the function that does the filtering is different than the one inside the myfunction.

要将上下文传递给另一个函数,可以使用bind。

myfunction(val){
    this.isLoading = true   
    var data =  this.myarray.filter((function(item) { 
      this.isLoading = false // throws error - Cannot set property 'isLoading' of undefined     
      return item.name == val;      
    }).bind(this));
    this.showdata = data[0]
    this.isLoading = false // this does not show effect
}

另外,如果您的环境支持ES6或使用babel,则可以使用箭头功能代替:

myfunction(val){
    this.isLoading = true   
    var data =  this.myarray.filter((item) => { 
      this.isLoading = false // throws error - Cannot set property 'isLoading' of undefined     
      return item.name == val;      
    });
    this.showdata = data[0]
    this.isLoading = false // this does not show effect
}
点赞
评论
那些过往
那些过往

Filter is not an asynchronous method, your program will wait till its completion. You simply have to remove the this.isLoading = false from inside the filter:

var data =  this.myarray.filter(function(item) { 
      return item.name == val;      
    });
this.isLoading = false;

this has a different context inside the function, and is not the same as that object referred to by the outer this

点赞
评论