首页 > 解决方案 > Aframe 自定义组件更新功能未触发

问题描述

当使用“setAttribute”时,我编写的自定义组件的更新功能没有触发,我不知道为什么。

最初,我认为这可能是因为我在将它们放入我的场景之前分别创建了自定义的“box-door”实体并更改了属性,但是即使在我等到这些实体被放入之后,更新功能仍然无法触发一个场景。

我也尝试过使用此处指定的事件侦听器 update is not fire in aframe component,但没有看到来自侦听器的任何调试消息。

我看到的唯一输出是初始化“box-door”实体后的单个“UPDATE FUNCTION HIT”消息。尽管所有 setAttribute 调用如下所示,我再也看不到输出了。

这是我的组件定义(注意 recreate_walldoor 创建网格并根据需要初始化对象):

AFRAME.registerComponent('box-door', {

schema: {
    width: {type: 'number', default: 10},
    height: {type: 'number', default: 5},
    depth: {type: 'number', default: 1},
    doorwidth: {type: 'number', default: 3},
    doorheight: {type: 'number', default: 4},
    dooroffset: {type: 'number', default: 3.5},
    color: {type: 'color', default: '#AAA'}
  },

init: function () {
    var data = this.data;
    var el = this.el;
    recreate_walldoor(el, data);

    this.el.addEventListener('componentChanged',function(e){
        console.log("LISTENER TRIGGERED");
    });

  },

    /*
   * Update the mesh in response to property updates.
   */
  update: function (oldData) {
    var data = this.data;
    var el = this.el;

    console.log("UPDATE FUNCTION HIT...");

    // If `oldData` is empty, then this means we're in the initialization process.
    // No need to update.
    if (Object.keys(oldData).length === 0) { console.log("exit"); return; }

    // Geometry-related properties changed. Update the geometry.
    if (data.width !== oldData.width ||
        data.height !== oldData.height ||
        data.depth !== oldData.depth) {
        console.log("DIMENSION CHANGE DETECTED");
        recreate_walldoor(el, data);
    }

    // Material-related properties changed. Update the material.
    if (data.color !== oldData.color) {
      el.getObject3D('mesh').material.color = data.color;
    }
  }
});

以下是属性更改的大致过程(这看起来不必要地令人费解,但这是因为我将跨文件的代码混合在一起以简化工作流程):

let div = document.createElement('a-entity');
var wall = document.createElement('a-entity');
wall.setAttribute('box-door', "");
wall.setAttribute('height', roomProps.h);
wall.setAttribute('width', roomProps.w);
wall.setAttribute('depth', roomProps.d);
wall.setAttribute('position', roomProps.center.clone().add(offset));
wall.setAttribute('rotation', {x:0, y:90.00 - theta*i, z:0});
wall.setAttribute('static-body', physics);
div.appendChild(wall);
ascene.appendChild(div);

标签: javascriptaframe

解决方案


这是因为您更新了实体属性而不是 box-door 属性的数据。

为此,您需要以下内容:

wall.setAttribute("box-door", {width: roomProps.w, height: roomProps.h});
// or
wall.setAttribute("box-door", "depth: " + roomProps.d);

然后它会触发 box-door 组件的更新功能。就像 Diego Marcos 所说,如果您提供一个故障示例来运行和编辑会更容易:)


推荐阅读