jQuery对象插件不是持久的

jQuery object plugin is not persistant

本文关键字:对象 插件 jQuery      更新时间:2024-03-29

我正在尝试用自定义属性和函数扩展jquery元素,这样我就可以随时跟踪我的元素并获取它们的自定义属性。

目前我已经这样做了:

 jQuery.fn.designerElement = function (tpl, cls) {
      this.__template = tpl
      this.des__class = cls;
      this.compile = function () {
          this.html(this.__template(this));
          return this;
      }
      return this;
  };
  var template = Handlebars.compile(
      '<div id="' + +new Date() + '" class="{{des__class}}"></div>'
  );
  var el = $('<div></div>').designerElement(template, "form-container");
  el.attr('id', "test");
  el.compile();
  $('body').append(el);

现在,如果我调用$('#test').compile(),它会说该方法未定义。

这是一把小提琴:http://jsfiddle.net/jmorvan/HLVj4/

为了解释我的上下文,我需要对象上直接可用的方法和属性,以便一些dataBinding工作,这就是为什么我不能使用.data()。在我看来,jquery插件将是最好的方法,但我在这里肯定遗漏了一些东西。

所以为了清楚起见,我需要能够访问这样的属性:$('#test').__template和函数。

谢谢你抽出时间!

我想您已经知道发生了什么,但这里有一个简短的解释:使用$('#test'),您将创建一个新的jQuery对象。它包含相同的元素,但您定义的是jQuery对象的属性,而不是元素。因此,您要问的是,是否有一种方法可以将功能添加到元素中,但要附加jQuery对象。在jQuery中data()毕竟可以用来做这个:

jQuery.fn.designerElement = function (tpl, cls) {
    this.__template = tpl
    this.des__class = cls;
    this.compile = function () {
        this.html(this.__template(this));
        return this;
    }
    this.data('this', this);
    return this;
};

并用检索该对象

var test = $('#test').data('this');

这是小提琴

另一种解决方案是将所有这些对象存储在全局可用的数组或JSON对象中。