Reputation: 940
I want to build up a <select>
via XML data within my object
. I want to use the Prototype Pattern for all of this and I have to admit I'm very new at Patterns. Here's what I have:
HTML Sample:
<select id="ddFullName" name="Full_Name" ></select>
XML sample:
<names>
<nameDetails name="Name 01" phone="555-867-5309" email="[email protected]" />
<nameDetails name="Name 02" phone="555-867-5309" email="[email protected]" />
<nameDetails name="Name 03" phone="555-867-5309" email="[email protected]" />
<nameDetails name="Name 04" phone="555-867-5309" email="[email protected]" />
<nameDetails name="Name 05" phone="555-867-5309" email="[email protected]" />
</names>
JavaScript Sample:
function buildNameDropdown(data, elem) {
this.data = data;
this.name = $(data).find('nameDetails');
this.elem = elem;
buildNameDropdown.prototype.init = function()
{
//Working as desired
$(this.elem).append($('<option value=""> ----- Select a Name ----- </option>'));
//Not working
$(this.name).each(function()
{
//$(this) = the object, not 'this.name'
$(this.elem).append($('<option value="' + $(this).attr('name') + '">' + $(this).attr('name') + '</option>'));
});
$(this.elem).combobox(); // from jQuery UI combobox extension
};
};
var myNameDropdown = new buildNameDropdown(data, "#ddFullName");
myNameDropdown.init();
how am I suppose to reference 'this' as the selector for the each function?
Upvotes: 1
Views: 1132
Reputation: 700352
Copy the this
reference to a local variable. That way it will be available in the closure of the callback function.
(Side note: You shouldn't set the prototype inside the constructor, that way you would reassign it for each instance that you create.)
function buildNameDropdown(data, elem) {
this.data = data;
this.name = $(data).find('nameDetails');
this.elem = elem;
};
buildNameDropdown.prototype.init = function() {
$(this.elem).append($('<option value=""> ----- Select a Name ----- </option>'));
var t = this;
$(this.name).each(function() {
$(t.elem).append($('<option value="' + $(this).attr('name') + '">' + $(this).attr('name') + '</option>'));
});
$(this.elem).combobox(); // from jQuery UI combobox extention
};
Upvotes: 2