对于您的画布使用Box实例作为上下文,您需要绑定它。
你可以尝试这样的事情:
function Box(boxData) {
// References the Box instance as I want.
console.log(this);
// I need to access this later...
var boxName = boxData.name;
// public property boxName
this.boxName = boxName;
var $canvas = $('#rm-' + boxData.id).find('canvas');
$canvas.on('mousedown', this.onMouseDownHandler.bind(this));
// ----------------------------------------------^
// this bind will prevent the event use canvas element as context
}
function Room() {
// some stuff
}
Room.prototype = new Box({name: 'this will always be my rooms box'});
Room.prototype.onMouseClickHandler = function(event) {
// 'boxName' is undefined as 'this' references 'event.target'
console.log(this.boxName);
}
现在你可以试试这个:
var foo = new Room();
foo.onMouseClickHandler();
而且您的控制台将记录this will always be my rooms box
。
你记住,房间扩展盒的一个实例,因此,如果你这样做:
foo.boxName = 'my name is what?!';
// you changed the this so the prototype will get the new value:
foo.onMouseClickHandler(); // 'my name is what?!'
EDIT(问题升级后)
只需使用this.boxName
代替var boxName
:
function Box(boxData) {
// References the Box instance as I want.
console.log(this);
// public property boxName
this.boxName = boxName;
}
如果你想为其他对象添加一个EventHandler,但保留你的Box控件文本你需要这样做:
var foo = newBox({boxName: 'foo'});
var bar = document.queryElementById('bar');
bar.addEventHandler('click', foo.onMouseClickHandler.bind(foo));
现在,如果你在bar
元素,从富的onMouseClickHandler点击,将保持它的上下文。点击事件将通过抛出参数。
你是如何执行你的Box.onMouseClickHandler?我认为你没有把它绑定正确,但需要一个例子来找出你得到错误的地方。请给出一个使用示例。 –
更新了事件监听器 – user1960364