我正在尝试在一个框架中创建一个自定义事件dataReady
,该事件将在成功下载几个不同的数据源时发出。我希望多个其他组件监听此事件,然后使其元素父项变为可见或执行其他操作。
在下面的示例代码中,在发出事件之前添加eventListener
(使用console.log()
测试),但在发出事件时不调用元素上的侦听器函数。我觉得所有的部件都已就位,但它只是不能正常工作。任何想法都会受到高度赞赏吗?
组件1附加到<a-camera data-controller></a-camera>
AFRAME.registerComponent('data-controller', {
init: function () {
var el = this.el;
},
update: function () {
async.eachSeries(['api-1', 'api-2'],
function (item, cb) {
console.log(item);
cb();
},
function (err) {
if (err) {
throw new Error('Error retrieving data from server');
}
console.log("emitting the event");
this.el.emit("dataReady", {value: 2}, false);
}.bind(this));
}
});
组件2附加到<a-entity geometry="primitive:plane" road></a-entity>
AFRAME.registerComponent('road', {
schema: {
width: {type: 'number', default: 4},
height: {type: 'number', default: 4}
},
init: function () {
var data = this.data;
var el = this.el;
// Update geometry props
el.setAttribute('geometry', 'width', data.width);
el.setAttribute('geometry', 'height', data.height);
console.log('adding an event listener');
el.addEventListener('click', function (event) {
console.log("we are ready to blast off b/c of event listened w/ detail value: " + event.detail.value);
});
}
});
index.html内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!--Vendor Scripts-->
<script src="./js/vendor/aframe.min.js"></script>
<script src="./js/vendor/async.min.js"></script>
<!--AFRAME Components-->
<script src="./js/components/road.js"></script>
<script src="./js/data-controller.js"></script>
</head>
<body>
<a-scene>
<a-entity geometry="primitive:plane" road></a-entity>
<a-camera data-controller></a-camera>
</a-scene>
</body>
</html>
答案 0 :(得分:2)
您可以依靠事件冒泡并在场景中聆听,并将实体存储在事件详细信息中,以便您知道它来自何处:
// data-controller component
this.el.emit('dataready', {value: 2, el: this.el})
// Event will bubble to the scene.
// road component
this.el.sceneEl.addEventListener('dataready', function () { // ... });
或者您可以将选择器属性类型的引用传递给要收听的实体:
// road component
schema: {
dataEl: {type: 'selector'},
width: {type: 'number', default: 4},
height: {type: 'number', default: 4}
},
init: function () {
// ...
this.data.dataEl.addEventListener('dataready', function () { // ... });
}
// <a-entity road="dataEl: [data-controller]"></a-entity>