Jay Sun
Jay Sun

Reputation: 1601

Javascript/jQuery object coding issue

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?

Upvotes: -1

Views: 61

Answers (4)

Joseph Silber
Joseph Silber

Reputation: 219930

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

Upvotes: 0

Mrchief
Mrchief

Reputation: 76208

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

Upvotes: 2

Maxx
Maxx

Reputation: 4072

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

e.html(); 

there instead

Upvotes: 0

pimvdb
pimvdb

Reputation: 154818

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.

Upvotes: 2

Related Questions