2017-07-29 66 views
1

同时学习Aframe/Javascript。了解组件

试图写我自己的组件,它改变对象的半径2点击,但如果如果对象的半径已经是2,那么它应该减少半径1

我将如何引用球体对象,我试图改变组件的半径。

谢谢

这是我的组件逻辑。

AFRAME.registerComponent('change-radius', { 

schema: { 
    radius: {type: 'int'} 
}, 

init: function(){ 
    var data = this.data; 
    this.el.addEventListener('click', 

    function(){  
     if (data.radius === 1) { 
      this.setAttribute('radius', data.radius); 
      console.log('THIS ONE'); 
     } else { 
      this.setAttribute('radius', 1); 
      console.log('NO !!!! THIS ONE'); 
     } 
    }) 
} 
}); 

这是我的球体代码。

<a-sphere id="sphere" change-radius="radius: 2" change-color="color: #0000FF" color="#F44336" radius="1" position="0 2 -4"></a-sphere> 

回答

0

从组件中访问球体对象是scope的问题。
- 对于附件,this.el是球体元素。
- 在this.el.addEventListener();内,this指的是球体元素,因为听众的作用范围是this.el。如果是在别的地方定义,你可以bind它(为了保持this范围),或从听者
称之为 - 否则,你就需要做一个let el = this.el参考,以便在你的舒适访问元素

当然你可以使用任何对象document.querySelector('cssSelector)


我建议做,如果球被放大或布尔开关检查没有,则设置半径,并相应地布尔:

init: function(){ 
    var data = this.data; 
    let el = this.el; 
    let enlarged = false; 
    this.el.addEventListener('click',function(){ 
    //BOOL SWITCH 
    if(!enlarged){ 
     data.radius = 2; 
    } else { 
     data.radius = 1; 
    } 
    // STATE CHANGE, AND RADIUS CHANGE 
    enlarged != enlarged; 
    el.setAttribute('radius',data.radius); 
    } 
    }) 
} 

伊莫这是蓓蒂而不是实际的半径检查,因为它比检查对象的属性更快地获得布尔状态。

您可以检查是否data.radius == 1,然后相应地更改半径,可能会更短,但这取决于您