1

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?

3
  • doesn't feel clunky to me... Commented Sep 11, 2013 at 16:12
  • why don't you just do the .append within the showTable function? Commented Sep 11, 2013 at 16:15
  • also, why does showTable care about what body is at all? Commented Sep 11, 2013 at 16:21

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Alnitak from the doc Within the function, this refers to the current element in the set did I misunderstand it
no, I think your right, I upvoted the comment, then thought about it and $(this) will be the body.
ah, ok, a special case I didn't know about - it seems that .append will indeed set the context if you pass it a function reference. However note that it will be set to the current jQuery element, and not whatever the value of this was when you referenced this.showTable, that being the mistake most people make when they pass a reference to a member function.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.