lolka_bolka lolka_bolka - 6 months ago 21
Javascript Question

Plugin method undefined

I am trying to create my first plugin, and when I add an item the

add
function called, so the object logged, but get error about
onAdd is undefined
(see below)

Here is the plugin

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


Here is the console:


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

TypeError: settings.onAdd is undefined


Can somebody enlighened me, why is there no
onAdd
function in my
settings
?

Answer

You are not including original settings object when you extending it. Also I advise you to create this.settings field to keep default settings separate:

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