對於您的畫布使用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