-1

So I have a newly created Javascript object called EditableObject in my custom .js file

function EditableObject(e, dv, i) {
this.element = e;
this.default_value = dv;
this.set = 0;
this.id = i;
alert(this.element.html());
this.element.click(function (event) {
 alert(this.element.html());
});

}

In my main page, I have a div called "field" that has the text "yeah" in it like such:

 <div id="field">yeah</div>

In the script portion of my main page, I've got:

var t = new EditableObject($("#field"), "value", 1);

When the page loads, there is an alert box that says "yeah". But when I click on the div, I get an error saying that "this.element is undefined". Why is this happening?

asked Aug 23, 2011 at 17:19

4 Answers 4

2

Inside your click handler, this refers to a different scope (depending on browser, it'll be the event object or the current function). You need a closure to access parent scope's this:

var self = this;
this.element.click(function (event) {
 alert(self.element.html());
});
answered Aug 23, 2011 at 17:23
Sign up to request clarification or add additional context in comments.

Comments

2

The thing with this is that it differs in each function depending on the context. In jQuery bind functions, it is the element itself so the most straight-forward solution is:

this.element.click(function (event) {
 alert($(this).html());
 // this is element, $(this) is jQuery object containing element
});

So currently, this refers to the element, which differs from e.g. the line

this.id = i;

where it refers to the instance of EditableObject, because there you use this in a different function.

answered Aug 23, 2011 at 17:21

Comments

0

The this in your click function refers only to the click itself. I believe you can use

e.html(); 

there instead

answered Aug 23, 2011 at 17:23

Comments

0

this inside of your click handler refers to the DOM object, not the instance of EditableObject.

You could modify it like this:

this.element.click(function (event) {
 alert($(this).html());
});
answered Aug 23, 2011 at 17:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.