[英]Mootools onClick send object
我試圖將一個對象從自身自身發送到另一個對象。
var Tile = new Class({
initialize : function(){
this.inner = new Element(...);
this.inner.addEvent('click', function() {
popup.open(this);
});
}
});
如果我從Tile out op Popup警報任何membervariable,則在警報“未定義”。 我究竟做錯了什么?
var Popup = new Class({
initialize : function(){
},
open : function(tile) {
alert(tile.width);
}
});
親切的問候!
當你通過this
給popup
對象,要傳遞的元素本身(我相信是你的意圖)。 但是,元素默認情況下不具有稱為width
的屬性。
也許您正在尋找getSize();
? 這將返回兩個屬性的對象( x
和y
),分別對應於元素的寬度和高度。
我已將您的代碼近似為以下jsFiddle,請嘗試一下: http : //jsfiddle.net/g4SmJ/
作為參考,這是新的Popup
類代碼:
var Popup = new Class({
initialize : function(){
},
open : function(tile) {
size = tile.getSize();
console.log(size); // console.log provides a nicer interface for debugging, you can pass objects into it! Use the Chrome Inspector or Firebug to see its output.
alert(size.x);
}
});
針對您的評論:
哦,ups我不是要提醒Doms寬度的,對此深表歉意。 我發布的是來自完整對象的較小代碼。 Width實際上是Tiles中定義的成員,我想從彈出窗口中發出警報
在這種情況下,則在將調用發送到.open();
,您this
傳遞給了函數調用,但沒有傳遞Tile
對象 ! 相反,您傳遞了創建的inner
元素。
從而重寫Tile
:
var Tile = new Class({
initialize : function(){
var self = this;
this.inner = new Element(...);
this.inner.addEvent('click', function() {
popup.open(self);
});
}
});
我想您正在尋找發送Tile
實例的機會。 就像上面的答案一樣,當您在addEvent
方法內部發送this
時,您將發送調用事件的元素本身:在您的情況下,您將發送inner的實例,因為您定義了onclick。
如果要發送切片實例,則有兩個選項:
1)綁定到此函數-意思是“連接”您當前所在的范圍(並在事件中):
var Tile = new Class({
initialize : function(){
this.inner = new Element(...);
this.inner.addEvent('click', function() {
popup.open(this); // <- now this is 'Tile' instance
}.bind(this)); //bind this to click
}
});
2)將實例保存在函數范圍之外,並在內部使用它:
var Tile = new Class({
initialize : function(){
this.inner = new Element(...);
var self = this; //save the this to var 'self'
this.inner.addEvent('click', function() {
popup.open(self); //use self which holds the Tile instance
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.