[英]OO Javascript / jQuery event click handler
I'm new on JS developing, I'm trying to use OO Javascript using "classes", I have a class named "Timeblock", with it constructor: 我是JS开发的新手,我正在尝试通过“类”使用OO Javascript,我有一个名为“ Timeblock”的类,并带有构造函数:
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上的类构造函数中添加click事件侦听器,我尝试过:
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');
在Chrome中进行调试时,我在this.element.addClass('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. 检查对象,我可以阅读this.element: jQuery.fn.init[0]
,但我无法使其正常工作。
Even in console when I type this.element
I get undefined
, but if I type this.occupied
I get false
即使在控制台中,当我键入this.element
时,我this.element
得到undefined
,但是如果我键入this.occupied
我将得到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. 我如何使它起作用?,我已经搜索了很多,但是找不到学习OO Javascript的任何好材料。
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. 我修复了它们,并留下了解释的说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.