How to change dynamically the text value of an <a-text>? - aframe

I want to make a dynamic digital clock in A-Frame. I'm using a text element but I can't change its text by setting the property in JS. I can still change others attributes like the color.
html:
...
<a-text id="clock" clock-text value="00:00" position="2.45 0 0.01" color="#FFFFFF" align="right"></a-text>
...
js:
...
AFRAME.registerComponent('clock-text', {
init: function() {
var el = this.el;
el.setAttribute('value', '20:30');
el.setAttribute('color', 'black');
},
update: function() {
el.setAttribute('value', '20:30');
}
});
You can get the full code in the jsfiddle I'm using.

So I think this is a race condition issue, since there's actually two updates going on in a-text, when it initializes and when it receives the new value (causing a component update to be called).
the text component does emit one event called 'textfontset' when updateFont gets called from its init.
Using that event, you can start your clock after that event is emitted
AFRAME.registerComponent('clock-text', {
init: function() {
var el = this.el;
this.ready = false;
el.addEventListener('textfontset', function() {
this.ready = true;
}.bind(this));
},
tick: function() {
var el = this.el;
if (!this.ready) {
return;
}
el.setAttribute('value', '20:30');
}
});
https://jsfiddle.net/xcofjjm9/1/

Related

meteor emit event then used by aframe eventlistener

I have an aframe object in main.html:
<a-gltf-model id='player1' foobox playmyclip src="#myMixBun" ></a-gltf-model>
I want to have it perform a gltf clip animation when the eventListener ‘driveplay’ is emitted.
In foofile.js:
AFRAME.registerComponent('playmyclip', {
init: function () {
var el = this.el;
el.addEventListener('driveplay', function () {
el.setAttribute('animation-mixer', {clip: 'Drive', loop: 'once'});
});
}
});
Currently I have it so when the j key is hit ‘driveplay’ is emitted:
AFRAME.registerComponent('foobox', {
init: function() {
var el = this.el
var swingno = 0;
self = this;
document.addEventListener('keydown', (event) => {
const keyName = event.key;
if (keyName === 'j') {
el.emit('driveplay',{},true);
// code to store record of event in Mongo for second player
var playerid = self.el.getAttribute('id');
var playerMid = Games.findOne({name: playerid})._id;
Games.update({_id: playerMid},{$set:{swings : swingno}});
swingno = swingno + 1;
}
})
}
});
But I also need to have the animation to happen at the same time on player2‘s screen. So in the above code I increment a variable in Mongo every time the animation happens. Then in main.js meteor automatically emits an event whenever “swingno” changes in Mongo.
main.js:
import {EventEmitter} from 'meteor/raix:eventemitter';
Event = new EventEmitter();
var swingcnt1 = 0;
Template.hello.helpers({
counter() {
if (Games.findOne()) //mongo is ready to access
{
var plyr1Swing = Games.findOne({name: "player1"}).swings;
if (plyr1Swing !== swingcnt1) {
Event.emit('driveplay',{},true);
swingcnt1 = plyr1Swing;
console.log(“this shows on player2’s console automatically”, swingcnt1);
}
}
else {null}
return { ........};
},
When player1 hits the “j” key the animation happens correctly on his screen, plus the event is recorded in Mongo, and player2 receives the updated Mongo value (since it show in the console.log).
The problem is the
Event.emit('driveplay',{},true);
statement doesn’t trigger the animation in player2‘s screen. This is a little tricky, since I need meteor’s “raix:eventemitter” package to create an event that the aframe event listener can see. It’s possible I’m not actually emitting an event at all, since I don’t know how to test if it’s working. Or possibly aframe can’t see the emitted event.
Possibly there’s an easier way of doing this. Thanks for any help.
SOLVED The solution was to use the listener code from meteor’s raix:eventemitter package inside Aframe’s component.
https://atmospherejs.com/raix/eventemitter
AFRAME.registerComponent('playmyclip', {
init: function ()
var el = this.el;
listener = function() {
el.setAttribute('animation-mixer', {clip: 'Drive', loop: 'once'});
};
Event.on('driveplay', listener);
}
});
Plus the foobox component no longer needs:
if (keyName === 'j') {
el.emit('driveplay',{},true);
Both player1 and player2 get the animation event from
Event.emit('driveplay',{},true);
in main.js when the meteor helper notices a change in the mongodb.

A-Frame : How to rotate a distant component with the raycaster?

In Aframe, is there a way to use the controller to rotate a distant component with the raycaster ?
Yes. cursor entity, with raycaster, and class='clickable' like this
<a-entity id="mouseCursor" cursor="rayOrigin: mouse" raycaster="objects:
.clickable"></a-entity>
then add a custom component on the object you want to spin, that listens for the mouse event, and then spins the object, until the mouse Leave event occurs. like this
AFRAME.registerComponent('over-listener', {
schema:{
mouseover:{type: 'boolean', default: false}
},
init: function () {
var el = this.el; // reference to the entity that contains this component
var data = this.data; // reference to the properties of this component.
// Listen for mouseenter event
this.el.addEventListener('mouseenter', function (evt) {
// You can't change the property directly. You must use setAttribute.
el.setAttribute('over-listener','mouseover', true);
// Change the color of the button to indicate rollover state is on.
el.setAttribute('material','color','#55ee00');;
});
// Listen for mouseleave event
this.el.addEventListener('mouseleave', function (evt) {
el.setAttribute('over-listener','mouseover', false);
el.setAttribute('material','color','orange');
});
},
tick: function(){ // called every frame
if(this.data.mouseover){ // Check the mouseover state
let elOcta = document.querySelector('#octahedron');
let rot = elOcta.getAttribute('rotation');
elOcta.setAttribute('rotation',{x: rot.x, y: rot.y , z: rot.z + 1});
}
}
});
here is a glitch
https://glitch.com/~rollover-rotate

Is it possible to display a UI transition to reflect changes in a collection with meteorjs?

I would like to display a pulse transition when my collection change.
In my html file, I have that:
<template name="menuItemTag">
<div class="app-menu-item-tag ui label">{{ count }}</div>
</template>
In my js file, I expose the count variable for my template like that:
Template.menuItemTag.count = function() {
return MyCollection.find().count();
};
With that the count change in the ui when the collection is updated.
Now, I would like to display a pulse transition on my div label each time the count value change.
I tried to use the cursor.observe
Template.menuItemTag.rendered = function() {
MyCollection.find().observe({
added: function (id, user) {
$('.app-menu-item-tag:nth(0)').transition('pulse');
},
removed: function () {
$('.app-menu-item-tag:nth(0)').transition('pulse');
}
});
};
Unfortunately, it is call too many times when the template is rendered the first time.
If initialy I have 40 items in my collection, the transition is played 40 times...
Is there a clean way for playing a ui transition on changes and avoid the collection initialisation?
Try this:
Template.menuItemTag.count = function() {
return Session.get('count');
};
Template.menuItemTag.rendered = function() {
this.countComputation = Deps.autorun(function() {
Session.set('count', MyCollection.find().count());
$('.app-menu-item-tag:nth(0)').transition('pulse');
});
};
Template.menuItemTag.destroyed = function() {
this.countComputation.stop();
};
Thanks sbking for your answer, I still have a problem on initialization of the collection.
I propose below to defer the first animation util the collection will be completely filled:
Template.menuItemTag.count = function() {
return Session.get('count');
};
Template.menuItemTag.rendered = function() {
var that = this;
this.countComputation = Deps.autorun(function() {
Session.set('count', MyCollection.find().count());
// Cancel playing UI transition. The collection is not completely initialized
if (that.handleTimeout) {
Meteor.clearTimeout(that.handleTimeout);
}
// Play the UI transition without the timeout if the collection is initialized
if (that.noNeedTimeoutAnymore) {
$('.app-menu-item-tag:nth(0)').transition('pulse');
}
// Tentative to play the UI transition during the collection feeding
else {
that.handleTimeout = Meteor.setTimeout(function() {
$('.app-menu-item-tag:nth(0)').transition('pulse');
// At this point we know that the collection is totaly initialized
// then we can remove the timeout on animation for the future update
that.noNeedTimeoutAnymore = true;
}, 1500); // You can adjust the delay if needed
}
});
};
Template.menuItemTag.destroyed = function() {
this.countComputation.stop();
};

Deep link to a position in a page, using Meteor JS

I have a meteor app with multiple pages. I want to be able to deeplink to an anchor somewhere halfway the page.
Traditionally, in normal html, you'd make an somewhere in your page, and link to it via /mypage.html#chapter5.
If I do this, my meteor app won't scroll down to that spot.
What is the best approach around this?
#Akshat 's answer works for on the same page, but what if you want to be able to pass around a url w/ a "#" in it? I did it how the meteor docs did.
Template.myTemplate.rendered = function() {
var hash = document.location.hash.substr(1);
if (hash && !Template.myTemplate.scrolled) {
var scroller = function() {
return $("html, body").stop();
};
Meteor.setTimeout(function() {
var elem = $('#'+hash);
if (elem.length) {
scroller().scrollTop(elem.offset().top);
// Guard against scrolling again w/ reactive changes
Template.myTemplate.scrolled = true;
}
},
0);
}
};
Template.myTemplate.destroyed = function() {
delete Template.myTemplate.scrolled;
};
Stolen from the source to the meteor docs.
Are you using some kind of javascript router? Meteor Router?
You could use something like a javascript based scrolling method. One such example is with JQuery: (You can place this in your link/buttons click handler)
Template.hello.events({
'click #theitemtoclick':function(e,tmpl) {
e.preventDefault();
$('html, body').animate({
scrollTop: $("#item_id").offset().top
}, 600);
}
});
Then tag your html item where you would put your anchor with the id:
<h1 id="item_id">Section X</h1>
Currently, there's an issue in IronRouter where the hash is removed from the url. This is discussed here and here. Fortunately there is a fix even though it doesn't appear to be in the stable version.
My Iron Router solution with traditional anchor tags:
1) Apply the IronRouter fix above
2)
Router.configure({
...
after: function () {
Session.set('hash', this.params.hash);
},
...
});
3)
function anchorScroll () {
Deps.autorun(function (){
var hash = Session.get('hash');
if (hash) {
var offset = $('a[name="'+hash+'"]').offset();
if (offset){
$('html, body').animate({scrollTop: offset.top},400);
}
}
Session.set('hash', '');
});
}
Template.MYTEMPLATE.rendered = function (){
anchorScroll();
};
Unfortunately this has to be set in each template's .rendered() otherwise the anchor tag is not guaranteed to be in the DOM.
For better or worse this will scroll again with a code push.
Mike's Answer didn't quite work for me. The hash was returning empty in the onRendered callback. I nested the code in an additional Meteor.setTimeout
fyi I'm using Blaze.
Below worked like a charm :)
Template.myTemplate.onRendered(function() {
Meteor.setTimeout(function(){
var hash = document.location.hash.substr(1);
if (hash && !Template.myTemplate.scrolled) {
var scroller = function() {
return $("html, body").stop();
};
Meteor.setTimeout(function() {
var elem = $("a[name='" + hash + "']");
if (elem.length) {
scroller().scrollTop(elem.offset().top);
// Guard against scrolling again w/ reactive changes
Template.myTemplate.scrolled = true;
}
},
0);
}
},0);
});
Template.myTemplate.destroyed = function() {
delete Template.myTemplate.scrolled;
};

how to trigger JQuery .draggable() on elements created by templates?

I have a standard template in an Html file like:
<template name="cards">
{{#each all_cards}}
{{> card_item}}
{{/each}}
</template>
<template name="card_item">
<div class="card" style="left:{{position.x}}px; top:{{position.y}}px">
{{title}}
</div>
</template>
I want to have the cards (css selector .card) become draggable with JQuery.
Now since Meteor automagically updates the DOM using the template, when and how do I know where to call .draggable() on what??
EDIT: This is so far my solution which makes pending movements on other client visible with a wobble animation (using CSS3):
Template.card_item.events = {
'mouseover .card': function (e) {
var $target = $(e.target);
var $cardContainer = $target.hasClass('card') ? $target : $target.parents('.card');
$cardContainer.draggable({containment: "parent", distance: 3});
},
'dragstart .card': function (e) {
Session.set("dragging_id", e.target.id);
$(e.target).addClass("drag");
pos = $(e.target).position();
Events.insert({type: "dragstart", id:e.target.id, left: pos.left, top: pos.top});
},
'dragstop .card': function (e) {
pos = $(e.target).position();
Events.insert({type: "dragstop", id:e.target.id, left: pos.left, top: pos.top});
Cards.update(e.target.id, {$set: {left:pos.left, top:pos.top}});
Session.set("dragging_id", null);
}
}
Events.find().observe({
added: function(event) {
if (event.type == "dragstart" && !Session.equals("dragging_id", event.id)) {
$("#"+event.id).draggable({disabled: true});
$("#"+event.id).addClass("wobble");
}
if (event.type == "dragstop" && !Session.equals("dragging_id", event.id)) {
$("#"+event.id).animate({left: event.left, top: event.top}, 250);
Events.remove({id:this.id});
$("#"+event.id).draggable({disabled: false});
}
}
});
EDIT: This approach doesn't seem to work in the latest versions of Meteor, e.g. v0.5.0. See my comment below.
Looks like we're working on similar things! I've got a working proof of concept for a simple Magic: The Gathering app. Here's how I have dragging implemented at the moment:
In a <head> section in one of your html files, include the jQuery UI script:
<script src="jquery-ui-1.8.20.custom.min.js"></script>
Then, in a js file, make sure elements become draggable on mouseover (note: this is sub-optimal on touchscreens since it requires two touches to drag... I'm looking for a better touchscreen solution):
Template.card_item.events['mouseover .card, touchstart .card'] = function (e) {
var $target = $(e.target);
if (!$target.data('isDraggable')) {
$target.data('isDraggable', true).draggable();
}
};
And finally, handle the drag and dragstop events:
var prevDraggedTime = 0
Template.card_item.events['drag .card'] = function (e) {
// get the cardId from e
var now = new Date().getTime();
var position;
if (now - prevDraggedTime > 250) {
position = $(e.target).position();
Cards.update(cardId, {$set: {x: position.top, y: position.left}});
prevDraggedTime = now;
}
}
Template.card_item.events['dragstop .card'] = function (e) {
// get the cardId from e
var position = $(e.target).position();
Cards.update(cardId, {$set: {x: position.top, y: position.left}});
}

Resources