Reputation: 2077
I'm new on JS developing, I'm trying to use OO Javascript using "classes", I have a class named "Timeblock", with it constructor:
var Timeblock = function(occupied, on, element) {
this.occupied = occupied;
this.on = on;
this.room_id = 0;
this.element= element;
}
I've created an object this way:
timeblock = new Timeblock(false, false, $('#element'));
Everything works at this point, now I'm trying to add a click event listener to the class constructor on its element var, I tried:
var Timeblock = function(occupied, on, element) {
this.occupied = occupied;
this.on = on;
this.room_id = 0;
this.element = element;
timeblock = this;
this.element.click(function() {
timeblock.update();
});
}
Timeblock.prototype.update = function() {
if (!occupied) {
this.element.addClass('on');
}
}
When debugging in Chrome, I put a breakpoint on this.element.addClass('on');
inspecting the object I can read this.element: jQuery.fn.init[0]
and I can't get it to work.
Even in console when I type this.element
I get undefined
, but if I type this.occupied
I get false
My question is, why I'm getting undefined? how can I make it work?, I've searched and searched but can't find any good material to study OO Javascript.
Upvotes: 0
Views: 198
Reputation: 33399
var Timeblock = function(occupied, on, element) {
this.occupied = occupied;
this.on = on;
this.room_id = 0;
this.element = element;
var timeblock = this; // need var statement
this.element.click(function() {
timeblock.update();
});
}
Timeblock.prototype.update = function() {
if (!this.occupied) { // forgot this
this.element.addClass('on');
}
}
Two errors. I fixed them, and left comments explaining.
Upvotes: 4