Ho queste due funzioni Javascript che sono uguali ad eccezione delle variabili
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();
}
}
Sono events
gestori e come puoi vedere hanno solo variabili diverse, ma gli algoritmi sono gli stessi. Come scriveresti solo una funzione per ottimizzare il codice?