Is it possible to access the DOM element 'this' in the non-function argument of a parameter in a jQuery plugin?

I have a potentially weird question about this and jQuery plugins

As I understand it, the following is a very simple jQuery plugin:

 $.fn.clickclone = function(param){ return this.click(function(){ param.apply(this); }); }; 

(pretending to be a plugin that somehow extends click() .)

So, if I pass the function as an argument, it does what it needs and correctly calls this as a DOM node. Easy.

This is all clear to me.

What is unclear is there a way to pass an argument to a non-function plugin and is it correct to access this from the arguments? those. I could configure the plugin to do something like this:

 $("#foo").pluginname(["foo", $(this).text() ]); 

Such that for:

 <a href="/bar" id="foo">Bar</a> 

It would correctly pass the array to the plugin, and the second element in the array would return the value Bar ?

I do this mainly to provide syntactic sugar for my plugin, where you can pass the array as a shortcut (in addition to the usual callback function as the main function). In addition, I am losing access to using this . Hence my dilemma.

EDIT: This is evil, but it seems like one job is to pass the argument as a string and then eval . This is not an acceptable solution for me, but it illustrates what I would like to do:

 $.fn.clickclone = function(param){ return this.click(function(){ if(typeof param === "function"){ param.apply(this); } else if(typeof param[1] === "string"){ console.dir("This is evil: " + eval(param[1])); } }); }; 
+4
source share
1 answer

There is no general way to do this without a function, since in a purely mathematical sense, you are requesting an input function (i.e. the this function): something that depends on this certain way.

You may have cracked it with strings, but you will lose the flexibility of functions:

 $.fn.alertMe = function (methodToAlert) { alert(this[methodToAlert]()); }; // usage: $("#foo").alertMe("text"); $("#foo").alertMe("width"); 

And if you find that using an acceptable function, but the syntax for this confused, you can simply do the following:

 $.fn.alertMe = function (alertGetter) { alert(alertGetter($(this)); }; // usage: $("#foo").alertMe(function (x$) { return x$.text(); }); $("#foo").alertMe(function (x$) { return x$.width(); }); 

And for completeness, I think I should mention that you could probably get away with an eval based solution that looks something like $("#foo").alertMe("$(this).text()") , but eval is evil, and I will not write or condone the solution. EDIT: Oh, I see you did it in editing on your original post. Good work corrupting future generations;)

+2
source

All Articles