2011-04-23 52 views
1

我想要做的是一個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')); 
     },  

    ... 

    }); 

回答

2

你的.each是錯誤的。

Object.each(obj, function(el, key, obj) { 

}, bind); 

http://mootools.net/docs/core/Types/Object#Object:Object-each

雖然你確實有this.objects爲陣,沒有注意到:)

Array.each(function(el, index) { 

}, bind); 
當你需要 this

綁定到元素上點擊,這很好。只需將this的副本存儲到self中,並改爲撥打self.info()。另外,保持綁定,並引用e.target作爲觸發元素代替,而this是你的實例

儘管它可能看起來「整潔」要儘量保持this綁定到類儘可能MooTools的核心開發者傾向於選擇因爲它避免了額外的回調綁定等(看看MooTools的來源,很常見的)

var self = this;方式,說你想擁有的單擊事件去直接的方法:

element.addEvent("click", this.info.bind(this));

它將把事件作爲第一個參數發送給info(所以參考event.target)。

+0

該foreach適合我。我實際上只有這樣做:'item.gfx.node.addEvent('click',this.info.bind(this,item));' – Mike 2011-04-23 17:08:44

1

bind通常適用的參數以及範圍(取決於實現),並允許你編寫function (raphaelObj, node) { ... }.bind(null, this, item.gfx.node)來綁定兩個參數。

+0

如果你使用的'bind'不允許,你可以考慮升級到:-),例如https://github.com/Raevel/Cactus/blob/master/ lib/Addon/Function.js#L81 – 2011-04-23 14:44:21