lundi 2 mars 2015

How to merge two functions that do same things with different variables


I have these two Javascript functions that are equal except for the variables



onClickVoteUp: function (e) {
var $target = $(e.target);
var upvoted = this.model.get("upvoted");
var downvoted = this.model.get("downvoted");
this.$el.find(".active").removeClass("active");
if(!upvoted){
if(downvoted) {
this.model.set("downvoted", false);
this.model.upvote();
}
this.model.upvote();
this.model.set("upvoted", true);
$target.addClass("active");
} else {
this.model.set("upvoted", false);
this.model.downvote();
}
},
onClickVoteDown: function (e) {
var $target = $(e.target);
var upvoted = this.model.get("upvoted");
var downvoted = this.model.get("downvoted");
this.$el.find(".active").removeClass("active");
if(!downvoted){
if(upvoted){
this.model.set("upvoted", false)
this.model.downvote();
}
this.model.downvote();
this.model.set("downvoted", true);
$target.addClass("active");
} else {
this.model.set("downvoted", false);
this.model.upvote();
}
}


They are events handlers and as you can see they only have different variable, but the algorithms are the same. How would you write only one function to optimize the code?





Aucun commentaire:

Enregistrer un commentaire