Question

I'm developing a custom jquery plugin with callback functionality. I have assigned plugin to 2 different element like

$("#id01").plug({
onsave: function(res) { console.log(res); }
});

$("#id02").plug({
onsave: function(res) { console.log(res); }
});

if i make any changes in element 1 and click save, callback function onsave() will trigger on both the elements. Please help me to resolve this.

Here is the sample code:

(function($){
    $.fn.plug = function(options) {
        var param = $.extend({
            selector: this.selector,
            onsave:   function() {}
        }, options);

        $(".savebtn").live('click', function() {
            if(typeof param.onsave == 'function') {
                var data = value;
                param.onsave.call(this, data);
            }
        });

    }
}(jQuery));
Was it helpful?

Solution

So, as i said in the comment, you are making a live call on a selector, you are binding 2 events on 2 elements while you should bind 1 event on 2 elements. Here how you should do it.

First create your save button in a var outside the focus function :

var saveBtn = $('<a/>', {href : '#', class : 'savebtn', text : 'Save'});

Then append that button on focus :

$(parent).append(saveBtn);

The binding should look like this :

saveBtn.bind('click', function() {
    if(typeof param.onsave == 'function') {
        var data = param.selector;
        param.onsave.call(this, data);
    }
    return false;
});

Inside a plug-in, you should never make a call to a jquery selector, especially when you are dynamicly creating them.

That make me think, this line:

$(param.selector).live('focus'...

can be change to that :

this.bind('focus'...

It is optimal and it's not using a selector!

I almost forgot, here the fiddle : http://jsfiddle.net/beBpb/9/


A little side note on the "save the button in a var". That will allow you to remove and add the button without messing the binding. It almost optimise the plug-in since a direct binding is faster than a delegated binding (live).

Plus, you can easily remove the save button when click on "Save" with this.remove() (Fiddle). That is adding a good functionnality to your plug-in and is performancewise better than anything since you are caching the button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top