vaso123
vaso123

Reputation: 12391

Callback function in plugin

I am trying to write my first plugin in jQuery, and I am a little bit confused with the callbacks.

For me, it's seems that everything is fine, but surly it is not.

The logic is (what I supposed) is to create a global settings object. When instantiate the tokenizer settings will be extended / overwrote with given settings / options, so it should be override the onAdd here $('#xxx').tokenizer(...

After that I just add an item, but in the console it sad:

The item in onAdd
undefined

Here is a jsFiddle

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('The item in function add: ' + item);
        this.settings.onAdd.call(item);
    };

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

    return this;
};

var $tokenizer = $('#xxx').tokenizer({
    sourceSelector: 'group',
    onAdd: function (item) {
        console.log('The item in onAdd');
        console.log(item);
    }
});

$tokenizer.idName = 'groupId';
$tokenizer.add('abcdefg');

Upvotes: 3

Views: 43

Answers (1)

BenG
BenG

Reputation: 15154

call should be:-

this.settings.onAdd.call(this, item);

Syntax

fun.call(thisArg[, arg1[, arg2[, ...]]])

FIDDLE

Upvotes: 2

Related Questions