AFrame: Get the marker ID when markerFound listener is triggered

Viewed 321

I have an AR scene with several markers that show different 3d models when activated. Like this:

<a-scene embedded arjs>     
    <a-marker markerhandler preset="custom" type="pattern" url="Target1.patt" id="1">
        <a-image src="image1.jpg"></a-image>
    </a-marker>
    <a-marker markerhandler preset="custom" type="pattern" url="Target2.patt" id="2">
        <a-image src="image2.jpg"></a-image>
    </a-marker>
    <a-entity camera></a-entity>
</a-scene>

And the associated script:

<script>
AFRAME.registerComponent('markerhandler', {
    init: function () {
      this.el.sceneEl.addEventListener('markerFound', (e) => {
          alert(this.id); //This should show the id ("1" or "2" in the example)
      })
    }
  });
</script>

How do I recognize which target is triggered, and get the id? I tried everything and I'm going crazy, any help is appreciated. Thank you!

1 Answers

In this case this refers to the components body. Depending on the context this will refer to different contexts

AFRAME.registerComponent("foo", {
  init: function() {
    console.log("init", this) // this - components body
    this.el.addEventListener("loaded", function() {
      // this - the element which the listener is added to
      console.log("function callback", this)
    })
    this.el.addEventListener("loaded", evt => {
      // this - the components body, because of the arrow function
      console.log("lambda callback", this) 
    })
  }
})

That being said - you're looking for this.el.id, as you're missing the element reference. Check it out in the below snippet (bottom logs):

<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent("foo", {
    init: function() {
      console.log("init. id: ", this.el.id)
      this.el.addEventListener("loaded", function() {
        console.log("function callback. id: ", this.id)
      })
      this.el.addEventListener("loaded", evt => console.log("arrow func. callback. id: ", this.el.id));
    }
  })
</script>
<a-scene>
  <a-box id="one" position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" foo></a-box>
</a-scene>

Related