插件方法未定义

时间:2016-05-17 08:37:20

标签: jquery

我正在尝试创建我的第一个插件,当我添加一个项目时调用了add函数,因此对象已记录,但得到有关onAdd is undefined的错误(见下文)

这是插件

    $(function () {
    var settings = {
        onAdd: function () {},
        onRemove: function () {},
        sourceSelecter: null,
        targetSelector: null
    };

    $.fn.tokenizer = function (options) {

        settings = $.extend({
            targetSelector: this,
            idName: 'id'
        }, options);

        this.add = function (item) {
            console.log (settings)
            settings.onAdd.call(item);
        };

        this.remove = function (item) {
            settings.onRemove.call(item);
        };
        return this;
    };
}(jQuery));

这是控制台:

  

Object {targetSelector:Object,idName:" id",sourceSelector:" group" }

     

TypeError:settings.onAdd未定义

有人可以帮助我,我的onAdd中为什么没有settings功能?

1 个答案:

答案 0 :(得分:0)

扩展时不包括原始settings对象。另外,我建议您创建this.settings字段以保持默认settings分开:

$(function() {
  var settings = {
    onAdd: function() {},
    onRemove: function() {},
    sourceSelecter: null,
    targetSelector: null
  };

  $.fn.tokenizer = function(options) {
    this.settings = $.extend({}, {
      targetSelector: this,
      idName: 'id'
    }, settings, options);

    this.add = function(item) {
      console.log(this.settings)
      this.settings.onAdd.call(item);
    };

    this.remove = function(item) {
      this.settings.onRemove.call(item);
    };
    return this;
  };
}(jQuery));