Alex
Alex

Reputation: 68470

jQuery type function as a variable

can I create a variable that is a function of this type:

jQuery.fn.appendValueToTextArea = function(txt){
  return this.each(function(){
    this.value += txt;
  });
};

?

I tried putting a var in front of it but I get a error.

Upvotes: 0

Views: 9594

Answers (3)

Felix Kling
Felix Kling

Reputation: 816404

If you want to call a method on an element like you wrote in the comment, you definitely have to extend jQuery.func.

Maybe you just want to store the name in a variable?

var name = 'appendValueToTextArea'; 
element[name]('text');

The only other way is to store a reference to the function and use .call() or .apply():

var func = jQuery.fn.appendValueToTextArea = function(txt) {
    // ...
};

func.call(element, 'text');

Or (as I am not sure what you really want) you can assign the function to a variable first and then assign it to jQuery.fn.appendValueToTextArea:

var func = function(txt) {
    // ...
};

jQuery.fn.appendValueToTextArea = func;

Upvotes: 3

Demian Brecht
Demian Brecht

Reputation: 21368

What happens if you define the variable after the function has been defined?

i.e.

jQuery.fn.appendValueToTextArea = function(txt){
  return this.each(function(){
    this.value += txt;
  });
};

var fn = jQuery.fn.appendValueToTextArea;

Upvotes: 2

John Hartsock
John Hartsock

Reputation: 86872

jQuery.fn.appendValueToTextArea = function(txt){
  return this.each(function(){
    this.value += txt;
  });
};

//This would put the function above in a variable. 
//However, I'm not exactly sure what this gains you    
var myfunction = jQuery.fn.appendValueToTextArea;

Upvotes: 1

Related Questions