javascript - Manipulate object's property while in event handler -
i've learned scope reasons this
keyword inside event listener, embedded in object, doesn't refer global object rather element triggered event.
now, understand if want fetch property can save variable before event handler called. can if want manipulate property's value?
in following piece of code trying manipulate drugcount
property within removedrug
event listener.
var drugs = { drugs: $("#drugs_table"), drugrow: $("#drug").html(), drugcount: 0, init: function() { this.adddrugrow(); this.removedrugrowhandler(); }, adddrugrow: function() { this.drugcount++; this.drugs.append(this.drugrow.replace(/{{id}}/,this.drugcount)); $(".drugsselect").select2(); }, removedrugrowhandler: function() { drugcount = this.drugcount; // problematic solution, because retains inital drugcount. // i.e need way access "live" count within event $(document).on("click",".removedrug",function(){ if (drugcount>0) { $(this).parents("tr").remove(); this.drugcount--; // how should approach this? } }); } }
try this
var drugs = function() { var me = this; me.drugs = $("#drugs_table"); me.drugrow = $("#drug").html(); me.drugcount = 0; me.init = function() { this.adddrugrow(); this.removedrugrowhandler(); }; me.adddrugrow = function() { this.drugcount++; this.drugs.append(this.drugrow.replace(/{{id}}/,this.drugcount)); $(".drugsselect").select2(); }; me.removedrugrowhandler= function() { var drugcount = me.drugcount; $(document).on("click",".removedrug",function(){ if (drugcount>0) { $(this).parents("tr").remove(); me.drugcount--; } }); } }
Comments
Post a Comment