这是简化的代码:
<html>
<head>
<script type="text/javascript">
var ParentDiv = new Class ({
initialize : function(htmlElement) {
console.log('debug: parent object created');
$$('.childDiv').each(function(childDiv){
childDiv = new ChildDiv(childDiv);
})
htmlElement.addEvents({
'click': function (){
console.log('debug: clicked parent');
},
'testEvent' : function(){
console.log('debug: complex logic altering inner HTML of the element');
}
})
}
});
function initParent () {
$$('.parentDiv').each(function(parentDiv){parentDiv = new ParentDiv(parentDiv);})
}
var ChildDiv = new Class ({
initialize : function(htmlElement) {
console.log('debug: child object created');
htmlElement.addEvent('click', function (){
console.log('debug: clicked child');
this.addEvent('testEvent', function(){console.log('debug: grabbed an event in child element, fired by child element')})
this.fireEvent('testEvent');
})
}
});
document.addEvent('domready', function(){
initParent();
});
</script>
</head>
<body>
<div class="parentDiv">
<div>
<div>
<div>
<div class="childDiv">Clicky Thingy</div>
</div>
</div>
</div>
</div>
</body>
</html>
结果如下:父对象的事件监听器都没有捕获这两个事件,而捕获事件是我想要实现的目标。这种结构可能出现的情况:页面上有一堆控制元素,它们都触发自己的事件,而文档或任何其他类型的容器根据捕获的事件类型操纵其中的内容。
那么,有没有办法使用自定义事件使“调试:改变元素内部 HTML 的复杂逻辑”出现在控制台框中?
最佳答案
这有很多错误。为了让你的生活更轻松,不要使用这么多嵌套的匿名函数,它们可以工作,但有时很难理清。我清理了它并给你做了一个 fiddle ,这样你就可以看到它是如何工作的。
您需要了解事件绑定(bind)才能执行您想要的操作:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
此外,您没有在类上实现“事件”,因此您无法执行此操作。fireevent
几乎所有 mootools 类的良好开端都是这样的:
var ClassName = new Class({
Implements: [Options, Events],
options: {
},
initialize: function(options){
this.setOptions(options);
}
});
关于javascript - MooTools:如何使对象捕获其嵌套对象中发生的自定义事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15388071/