我想要做的是一個Mootools類和拉斐爾的組合。我得到的問題主要是我猜測mootools事件綁定。 我想追加一個事件到raphael元素(dom節點),並且在觸發事件時應該調用另一個類方法。 編碼沒有mootools類時,這是沒有問題的。但是這(正確的)方式我有一些問題。綁定事件時,raphael元素不能再使用,因爲「this」現在引用了mootools類。問題綁定Mootools事件和調用類方法
請看看這個代碼,我想你會明白我的問題是什麼:
// mootools class
var test = new Class({
...
initPlane: function() {
// just an JSON object array
this.objects = [{"pid":"2","sx":"685","sy":"498","dx":"190","dy":"540"},{"pid":"3","sx":"156","sy":"341","dx":"691","dy":"500"}];
// place the objects on stage and append some events to them
this.objects.each(function(item, idx){
item.gfx = this.gfx.image("assets/img/enemy.png", item.sx, item.sy, 32, 32);
// #### differnt approaches to bind the events. all not working
// first attempt with mootools event
item.gfx.node.addEvent('click', function(e) {
console.log(this.attr('x')); // not working because this is bound to the class i guess
this.info();
}.bind(this));
// second attempt with mootools event
item.gfx.node.addEvent('click', function(e) {
console.log(this.attr('x')); // not working
parent.info(this); // no binding and not working
});
// first attempt with raphael event
item.gfx.click(function(e) {
console.log(this.attr('x')); // works !
this.info(this); // not working because this refers to raphael element.
});
}.bind(this))
},
// this method should be called after click event and output element attribs
info: function(event) {
console.log(event.attr('x'));
},
...
});
該foreach適合我。我實際上只有這樣做:'item.gfx.node.addEvent('click',this.info.bind(this,item));' – Mike 2011-04-23 17:08:44