原型模式,在jQuery $ .each函数中使用'this'

时间:2013-04-25 19:46:45

标签: javascript jquery design-patterns prototype this

我想在<select>内通过XML数据构建object。我想在所有这些中使用Prototype Pattern,我不得不承认我在Patterns中非常新。这就是我所拥有的:

HTML示例:

<select id="ddFullName" name="Full_Name" ></select>

XML示例:

<names>
  <nameDetails name="Name 01" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 02" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 03" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 04" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 05" phone="555-867-5309" email="none@nothing.no" />
</names>

JavaScript示例:

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();

我怎么想把'this'作为每个函数的选择器?

1 个答案:

答案 0 :(得分:2)

this引用复制到本地变量。这样它就可以在回调函数的闭包中使用。

(旁注:你不应该在构造函数中设置原型,这样你就可以为你创建的每个实例重新分配它。)

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
};