Wednesday, May 16, 2012

How To Pass "this" to a Function in a Nested .each() loop within a .getJSON() method

So I know what the problem is, but I don't know the proper way (the syntax) to fix it.



If you take the code from "myFunction" and put it inside the .each loop where I am calling "myFunction" then my code works because "this" is being defined and is within the scope of the JSON object that I am referencing.



But, when I write my function and declare it outside the scope of the JSON object, then it no longer knows what "this" is and returns a value of "undefined".



How do I pass "this" as an argument to my function so that I can properly grab the values?



    $.getJSON('labOrders.json', function(json) {
var aceInhibitors = "",
antianginal = "",
anticoagulants = "",
betaBlocker = "",
diuretic = "",
mineral = "",
myFunction = function () {
aceInhibitors += "<div class='row drugLineItem'>",
aceInhibitors += "<div class='columns moneydot' style='background:none;'></div>",
aceInhibitors += "<div class='columns drugTitleWrap'>",
aceInhibitors += "<div class='row drugTitle'>"+this.name+"</div>",
aceInhibitors += "<div class='row drugDose'>"+this.strength+"</div>",
aceInhibitors += "<div class='columns'></div>",
aceInhibitors += "<div class='columns orderDeets dxRefill'>"+this.refills+"</div>",
aceInhibitors += "<div class='columns orderDeets dxPillCount'>"+this.pillCount+"</div>",
aceInhibitors += "<div class='columns orderDeets dxSig'>"+this.sig+"</div>",
aceInhibitors += "<div class='columns orderDeets dxRoute'>"+this.route+"</div>",
aceInhibitors += "<div class='columns orderDeets drugTab'>"+this.dose+"</div>"
}

$.each(json.medications, function(index, orders) {
$.each(this.aceInhibitors, function() {
myFunction();

});
$.each(this.antianginal, function() {

});
});

$('#loadMedSections').append(aceInhibitors);



});




No comments:

Post a Comment