Bilal Niaz Awan
Bilal Niaz Awan

Reputation: 21

using jQuery delegate in a JQuery plugin

If I am writing a jQuery plugin as

$.fn.newWin = function(docTypes) { 
                    $(this).live("click",function(){
                                    alert("I am done");
                    }); 
              };

This plugin can be invoked as

$("#content a, #partners a").newWin();

Basically what I want is to swap .live with .delegate. How can I achieve that as I have to pass the callee element string to the .delegate function also?

Upvotes: 2

Views: 930

Answers (3)

xbl
xbl

Reputation: 1

$.fn.newPlug = function(){
    var selector = $(this).selector;
    $(document.body).delegate(selector, 'click', function(){
        // do something...
    });
};

look at this!

Upvotes: 0

Tadeck
Tadeck

Reputation: 137340

It depends on what you want to achieve (the actual architecture of your plugin). But it may look as follows:

$.fn.newWin = function(elements_selector) {
    $(this).delegate(elements_selector, "click",function(){
        alert("I am done");
    });
};

and can be invoked like that:

$("#content, #partners").newWin("a");

In case of jQuery newer than 1.7 you should however switch to .on() instead of .live() or .delegate(). See documentation of .on() jQuery function.

Is that what you expected?

Upvotes: 1

genesis
genesis

Reputation: 50976

I wouldn't recommend you to use delegate here. If you can (as of jQuery 1.7), use .on() instead

$.fn.newWin = function(docTypes) { 
      $(this).on("click",function(){
            alert("I am done");
      }); 
};

Upvotes: 2

Related Questions