Chris C
Chris C

Reputation: 2013

How do you pass a JQuery object in a function as a parameter for that object's method call?

For example, I have a method showTable that takes a JQuery object, and the showTable call is a parameter for the append method of that same object.

This is the result I'm going for:

body.append (this.showTable(body));

showTable returns an HTML string to append to body. But I don't like typing body twice, it feels clunky. How do make it implicit that body is the variable to be passed?

Upvotes: 1

Views: 55

Answers (2)

000
000

Reputation: 27247

Let's start by rewriting it in fluent style:

this.showTable(body).appendTo(body)

But that doesn't really answer the question. I think it looks better.

To answer the question, I would write a helper function:

jQuery.fn.extend({
    appendTableTo: function(thing) { return this.showTable(thing).appendTo(thing) }
});
this.appendTableTo(body);

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the .append( function(index, html) ) variant here

body.append (this.showTable);

then inside

function showTable(){
    //here this points to the body element
}

Upvotes: 2

Related Questions