I have a javascript class that has a method that uses jQuery to send an Ajax request and handle the response.
The problem I am having is that I can’t figure out how to get the properties of the initial, parent class from within the jQuery functions. I have tried $(this).parent() but this doesn’t get what I need for some reason.
My code is below. Can anyone tell me how to get to the base class from this loop?
function companiesPage()
{
this.childCategoriesSelectid = '#childCategoryid';
this.setChildCategories = function()
{
$.ajax({
url: this.url,
dataType: 'json',
success: function(data)
{
$.each(data.childCategories, function()
{
$($(this).parent().childCategoriesSelectid)//problem here
.append(
$('<option></option>')
.attr('value', this.childCategoryid)
.text(this.name)
);
});
}
});
}
}
parent()is for DOM traversal. What you have is a scoping problem.The
thiskeyword does not always references the same object when entering a new function scope. That is the case when using jQuery’s.each()method which will setthisto the object/element being iterated.Looks like you’re using a constructor-instance pattern, so you just have store a reference to the original object that the
thiskeyword referenced to (the instance) through a var declaration. This reference will remain unchangeable in the scope chain:This way you will be able to access any of your instance’s public methods and properties anywhere inside of your instance.
ps. Instanceables/Constructors usually have the first letter upper-cased, by convention.