另一种不用lodash调用方法的方法

Another way to call method without lodash?

本文关键字:方法 调用 lodash 另一种      更新时间:2023-09-26

在我的流星应用程序中,这个带有方法调用的投票功能工作正常,直到我包含一个将lodash导出为var _ = runInContext();的兼容性脚本。现在我得到错误,_.contains不是一个函数。

有没有另一种方法来运行这个函数和调用没有_.contains ?

打开按钮:

"click [data-action='addLikes']": function (event) {
    event.preventDefault();
    var song = Songs.findOne({_id: this._id});
    upvote(song);
}
服务器方法:

upvote = function(currentSong){
  var user = Meteor.user();
  if(!user){
    return false;
  }
  if (currentSong) {
    if (_.contains(currentSong.voters, Meteor.userId())) {
      return false;
    }
    Songs.update(currentSong._id, {$addToSet: {voters: Meteor.userId()}, $inc: {likes: 1}});
  }
};

如果currentSong.voters只是一个数组,您可以使用两种解决方案:

ES6 :

currentSong.voters.includes(Meteor.userId())

ES5 :

currentSong.voters.indexOf(Meteor.userId()) > -1

或简写的

~currentSong.voters.indexOf(Meteor.userId())