2011-04-08 21 views
1

我創建在Mootools的一個新元素,其具有的事件,這樣的:在MooTools的:在元素構造活動

var div = new Element('div', { 
id: 'dynamic', 
'class': 'injected', 
styles: { 
    color: '#f55' 
}, 
html: 'Hong Kong Phooey, number one super guy. Hong Kong Phooey, quicker than the human eye. He\'s got style, a groovy style, and a car that just won\'t stop. When the going gets tough, he\'s really rough, with a Hong Kong Phooey chop (Hi-Ya!). Hong Kong Phooey, number one super guy. Kong Phooey, number one super guy. Hong Kong Phooey, quicker than the human eye. He\'s got style, a groovy style, and a car that just won\'t stop. When the going gets tough, he\'s really rough, with a Hong Kong Phooey chop (Hi-Ya!). Hong Kong Phooey, number one super guy.', 
events: { 
    click: function(event) { 
     alert('clicked'); 
    }, 
    mouseenter: function(event) { 
     var self = $('dynamic'); 
     self.setStyle('color', '#090'); 
    }, 
    mouseleave: function(event) { 
     var self = $('dynamic'); 
     self.setStyle('color', '#f55'); 
    } 
} 
}); 

div.inject(document.body); 

它是一個糟糕的技術來獲得具有自我股利= $(「動態」)每個事件?我試過

mouseenter: function(event) { 
     this.setStyle('color', '#090'); 
    }.bind(this) 

認爲「this」會引用我正在構建的元素。但相反,它指的是全球窗口。

我是否正確的做事?

謝謝!

回答

1

很好 - 在構造函數的情況下的實際元素之前它存在就不行,因爲你已經發現 - 這將範圍窗口或任何束縛了作用域鏈從你使用構造函數的地方開始。

有一個選擇器self = selectorbyid不是很好,如果你經常重複它並且關心性能,它不是很好。

要做到這一點的最快方法是參考event.target,這將是div - 或者將元素構造函數分解爲兩個,並在div爲對象時添加事件並且可以綁定它。

下降到使用event.target是如果您編程上想要通過div.fireEvent("click")調用它,這將失敗,因爲事件不會傳遞。但你可以做div.fireEvent("click", { target: div });和周圍那當然

得到的,因爲DIV是你已經有一個範圍的懸掛變量,你可以這樣做:

mouseenter: function(event) {   
    div.setStyle('color', '#090'); 
}, 
mouseleave: function(event) { 
    div.setStyle('color', '#f55'); 
} 
+0

非常感謝Dimitar的解釋! – 2011-04-08 13:08:56

3

你可以使用event.target

events: { 
    mouseenter: function(event) { 
     event.target.setStyle('color', '#090'); 
    }, 
    mouseleave: function(event) { 
     event.target.setStyle('color', '#f55'); 
    } 
} 
+0

非常感謝pleasedontbelong,這是做的很好的經濟的方式它。 – 2011-04-08 13:09:40