开发者

jQuery: Pass plugin a string reference to be used as object in plugin

开发者 https://www.devze.com 2023-03-02 01:24 出处:网络
This may be a little non-standard..... // JavaScript Document (function( $ ){ $.fn.editAsPage = function(options) {

This may be a little non-standard.....

// JavaScript Document
(function( $ ){
$.fn.editAsPage = function(options) {       
    var settings =  {};     
    if(options){ jQuery.extend(settings, options); }        
    return this.each( function(){           
        var el = jQuery(this);
        alert(settings.source.attr("class"));                         
    });
};
})(jQuery);

My question lies around the settings.source parameter. attr("class") is just an example, there are several attributes I need to get from a particular DOM element, but the user of the plugin may need to define which DOM element settings.source is.

So you say, just pass in an jQuery object. Where I run into a problem is that I, for one, want to reference the parent o开发者_Python百科f "this" in the plugin.

For example:

jQuery(".edit").editAsPage({
        'source':jQuery(this)                                                              
    });

Here, jQuery(this) won't refer to element with the .edit class since it will interpret it before calling the editAsPage function.

I guess the question is, can I pass a string to the editAsPage function to be interpreted as a jQuery object in the plugin?

This is a very simple example. The reason, I don't just use "this" inside the plugin, is because "source" could change. It may very well be something like:

'source':jQuery(this).parents("selector:first")

Not sure if that made any sense what I'm asking. It makes sense in my mind. :)

Thanks.


You need to be using callbacks for this. First step is to change your thinking of how this should work by making source a callback. Next you need to modify source to pass a new this definition using JS's call() mtheod (or apply() when applicable).

Your plugin code modified would look like:

(function( $ ){
$.fn.editAsPage = function(options) {       
    var settings =  {};     
    if(options){ jQuery.extend(settings, options); }        
    return this.each( function(){           
        var el = jQuery(this);
        settings.source.call(this, el);                       
    });
};
})(jQuery);

Your user then would use it like this:

$('.edit').editAsPage({ 
  source:function(){
    $('.parent').append('<strong>#'+$(this).parent().attr('id')+'</strong>');
    $('.id').append('<strong>#'+$(this).attr('id')+'</strong>');
  }
});

See a live example here: http://jsbin.com/ipafe4

Play with the live example here: http://jsbin.com/ipafe4/edit

What we did was change what "this" meant then gave it back to the source function / callback the user is defining.

Info on call and apply: http://www.pagecolumn.com/javascript/apply_call.htm

0

精彩评论

暂无评论...
验证码 换一张
取 消