EaselJS : Help understanding animationend event - events

In trying to figure out how to start and stop Sprite animations from a SpriteSheet, I tried this:
// other code...
// define animations in SpriteSheet:
"animations": {"intro": [0, 19, "false"]}
// other code...
var spriteSheet = new createjs.SpriteSheet(data);
var intro = new createjs.Sprite(spriteSheet, "intro");
stage.addChild(intro);
createjs.Ticker.addEventListener("tick", stage);
intro.stop();
var btnStart = document.getElementById("btnStart");
btnStart.onclick = function() {
console.log("btnStart clicked");
intro.on("animationend", onStartAnimEnd);
intro.play();
};
function onStartAnimEnd(e) {
intro.removeEventListener("animationend", onStartAnimEnd);
console.log("Start anim ended");
}
In the above example, if the user clicks the btnStart button, the onStartAnimEnd callback fires indefinitely, even though by defining "false" in the animation configuration to signal we want to stop on the last frame, and the animation does in fact stop, and I'm removing the event listener in the first line of the callback.
If I add:
function onStartAnimEnd(e) {
intro.removeEventListener("animationend", onStartAnimEnd);
intro.stop();
console.log("Start anim ended");
}
The problem goes away, but that doesn't seem right... So, if I change the listener assignment of the animationend event from:
intro.on("animationend", onStartAnimEnd);
to:
ask.addEventListener("animationend", onAskAnimEnd);
...and with this change, the indefinite event captures goes away. So my questions are:
What's the difference with these two event listener assignments?
Is this animationend event continually firing in the background because we're updating the stage on the tick event, even though nothing needs re-rendering?
Thanks for your time!

This is actually a duplicated question. As I answered you previous question, your animation definition is wrong, you need to use the boolean value (false) and not the string value ("false").
Now sure what ask is, but the method on is a wrapper for addEventListener, and where you can specify things such as the scope of the callback and if it will run only once. Take a look at the API to know more:
http://www.createjs.com/Docs/EaselJS/classes/EventDispatcher.html#method_on

Related

How to write a custom mouse wheel event handler in OrbitControls?

I'm working on a WebGL application using ThreeJS and OrbitControls. How do I write and make use of a custom event handler for wheel spin events?
Suppose my custom handler is
function custom_handleMouseWheel(event) { ... }
I tried adding it as a listener:
window.addEventListener("wheel", custom_handleMouseWheel);
but I suspect this adds my handler to a list of existing handlers (probably only one), and I'd have to remove the original handler. Not sure how to do that. And anyway, my handler never was called, which I checked for by adding a console.log("Wheel!") line to my handler.
Another thing I tried is to replace the handleWheelMouse method in the controls object, like this:
let original_handleMouseWheel;
function custom_handleMouseWheel(event) {
console.log("Custom Wheel!");
... fancy geometry calculations ...
original_handleMouseWheel(event);
}
// somewhere after defining scene, camera, renderer, etc...
controls = new THREE.OrbitControls( camera );
original_handleMouseWheel = controls.handleMouseWheel;
controls.handleMouseWheel = custom_handleMouseWheel;
but again the console.log line never executes.
What is the right way to go about doing this?
Just setting controls.enableZoom = false will stop the default zoom.
The default "wheel" listener is added to the "domElement" which should be the second parameter sent to the OrbitControls constructor.
Try renderer.domElement.addEventListener('wheel', custom_handleMouseWheel);

Deferred in click event with jquery for ui render

I have this code:
$("input#drawAllRoutes").click(function (e) {
console.log("drawAllRoutes: Start Drawing");
showWaitPanel();
...
//foreach routeElement add vector layer on map
...
console.log("drawAllRoutes: Ok ");
hideWaitPanel();
})
I would have this behavior:
show wait panel adding the correct class in a div: this is done by showWaitPanel();
after that I add an high number of vector layer in openlayers3 map
when done, the wait panel is set hide with hideWaitPanel() that remove a class from a div
The problem is that with this code, the UI is not rendered because the vectors drawing require more resources and so freeze the UI.
So I don't see the wait panel, and the UI is freezed until the vector layers are drawed on the map.
How can I render the wait panel before the drawings?
I have read about deferred method, but I don't know very well it.
Thanks for any support.
You probably just need to force each stage into a different event thread, which can be achieved in a couple of ways.
Using window.setTimeout()
This is simple and should work despite being syntactically ugly.
$("input#drawAllRoutes").click(function (e) {
console.log("drawAllRoutes: Start Drawing");
showWaitPanel(); // assumed to be synchronous.
window.setTimeout(function() {
...
//foreach routeElement add vector layer on map
...
hideWaitPanel(); // ok in same event thread unless vector rendering is itself asynchronous.
console.log("drawAllRoutes: Ok");
}, 0); // even with a timeout of zero seconds, the passed function will execute in a later event thread.
});
Using a promise
The nett effect here should be very similar to using setTimeout(), but it will work only if showWaitPanel() returns a promise, otherwise showWaitPanel().then() will throw an error. So you would need to amend your showWaitPanel() function.
$("input#drawAllRoutes").click(function (e) {
console.log("drawAllRoutes: Start Drawing");
showWaitPanel().then(function() {
...
//foreach routeElement add vector layer on map
...
hideWaitPanel(); // ok in same event thread unless vector rendering is itself asynchronous.
console.log("drawAllRoutes: Ok");
});
});
TBH, using a promise is overkill here. If it works, I would use setTimeout() despite its ugliness.

Unity onClick.addlistener not working

I load a Canvas prefab at runtime when an event occurs. The canvas simply has a Panel inside it, which in turn has 2 buttons. I'm trying to add OnClick events to both these buttons in the script, but it only works for the first button somehow!
I have the following two lines of code one after the other:
GameObject.Find("RestartButton").GetComponent<Button>().onClick.AddListener(() => RestartClicked());
GameObject.Find("ViewButton").GetComponent<Button>().onClick.AddListener(() => ViewClicked());
The callback only works for the RestartButton, and not for the ViewButton.
It may well be a very small thing, but I searched Google and Bing extensively and remain clueless, so any help would be appreciated.
Thanks!
Edit:
The script instantiates the prefab and tries to reference the two buttons in the prefab through GameObject.Find(), given that once Instantiate is called the Canvas should be active in the heirarchy.
I also opened up the part of the code that attaches buttons to the listener for debugging. I dont think it attaches the listener at all.
void Start () {
SetupScene();
var prefab = Resources.Load("RestartOrViewPrefab");
if (prefab == null)
{
Debug.LogAssertion("Prefab missing!");
return;
}
restartCanvas = (GameObject)Instantiate(prefab);
Button btn = GameObject.Find("ViewButton").GetComponent<Button>();
btn.onClick.RemoveAllListeners();
btn.onClick.AddListener(() => ViewToggle());
Button btn2 = GameObject.Find("RestartButton").GetComponent<Button>();
btn2.onClick.AddListener(() => RestartClicked());
}
private void RestartClicked()
{
Debug.Log("RESTARTING");
SetupScene();
}
private void ViewToggle()
{
Debug.Log("TOGGLE");
if (freshStart)
{
//Something here
freshStart = false;
}
else
{
//Something else here
freshStart = true;
}
}
So I took two days to solve my problem. Apparently, doing a GameObject.Find() for a GameObject within a prefab that you just instantiated doesn't work. We always need to use the GameObject that the Instantiate() method returns to find any component within the prefab.
The code I used to make my scene work may not be the best solution if your prefab is very big/complex (say you have 15 buttons and need to do something with one), but it sure does work. :)
I replaced the following lines of code:
Button btn = GameObject.Find("ViewButton").GetComponent<Button>();
btn.onClick.RemoveAllListeners();
btn.onClick.AddListener(() => ViewToggle());
Button btn2 = GameObject.Find("RestartButton").GetComponent<Button>();
btn2.onClick.AddListener(() => RestartClicked());
With the following lines of code:
Button[] buttons = restartCanvas.GetComponentsInChildren<Button>();
foreach(Button but in buttons)
{
if(but.gameObject.name == "RestartButton")
but.onClick.AddListener(() => RestartClicked());
else if(but.gameObject.name == "ViewButton")
but.onClick.AddListener(() => ViewToggle());
}
So I just reused the restartCanvas that I got a reference to.
restartCanvas = (GameObject)Instantiate(prefab);
Hope this helps someone. :)
I answered this on another post, but I'll answer it here for people that still need this info.
The GameObject your instantiated button is a child of must have a CanvasRenderer component on it.
I'm not sure why this works, but it does.
Once the parent of the button GameObject has the CanvasRenderer on it, you can call myButton.onClick.AddListener(() => MyMethod(MyArgs)); as you normally would.
Ok make sure you are not getting any null reference error, and check tht spelling of you buttons , output some debug logs in your second function to see if its even reaching there

Delay shared element transition to complete statelist animation

I've been trying out shared element transition on Lollipop. i have a recyclerview which loads some cards and one click the card expands to its details in the next activity.
I have set a ripple effect and a StateListAnimator on the card. But those are not visible cause the transition starts before these effects are completed.
Is there any way to delay the transition so that it can wait for the statelist animator and ripple to complete?
Here is the code I use
ActivityOptions options = null;
if (Utilities.isLollipop()) {
options = ActivityOptions.makeSceneTransitionAnimation(this, Pair.create(view, "hero_view"), Pair.create((View) fab, "fab"));
startActivity(detailIntent, options.toBundle());
}
Thanks in advance
I ended up using a work around, but I still would want to know what is the right way of doing this and therefore leaving the question open.
The work around I did was
1. remove the state list animator and add that as an animator in the onclick method.
2. Used a Handler to post a delayed call to the activity
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(SearxhJobs.this,JobsTypes.class);
startActivity(i);
}
}, 200);
P.S- I did end up removing the effect as it was not very intuitive.
The way that may help some that already have the Transitions setup in Second Activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().getSharedElementEnterTransition().setDuration(500);
getWindow().getSharedElementReturnTransition().setDuration(500)
.setInterpolator(new DecelerateInterpolator());
}

jQuery — trigger a live event only once per element on the page?

Here's the scenario
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
}
})
Here's some background
The custom event is from a plugin called inview
The actual issue is here http://syndex.me
In a nutshell, new tumblr posts are being infnitely scrolled via
javascript hack (the only one out there for tumblr fyi.)
The inview plugin listens for new posts to come into the viewport, if the top of an image is shown, it makes it visible.
It's kinda working, but if you check your console at http://.syndex.me check how often the event is being fired
Maybe i'm also being to fussy and this is ok? Please let me know your professional opinion. but ideally i'd like it to stop doing something i dont need anymore.
Some things I've tried that did not work:
stopPropagation
.die();
Some solutions via S.O. didnt work either eg In jQuery, is there any way to only bind a click once? or Using .one() with .live() jQuery
I'm pretty surprised as to why such an option isnt out there yet. Surely the .one() event is also needed for future elements too? #justsayin
Thanks.
Add a class to the element when the event happens, and only have the event happen on elements that don't have that class.
$("p:not(.nolive)").live(event,function(){
$(this).addClass("nolive");
dostuff();
});
Edit: Example from comments:
$("p").live(event,function(){
var $this = $(this);
if ($this.data("live")) {
return;
}
$this.data("live",true);
doStuff();
});
This one works (see fiddle):
jQuery(function($) {
$("p").live('customEvent', function(event, chkSomething) {
//this particular custom event works with live
if (chkSomething) {
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).bind('customEvent', false);
}
});
function doStuff() {
window.alert('ran dostuff');
};
$('#content').append('<p>Here is a test</p>');
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
});
This should also work for your needs, although it's not as pretty :)
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething && $(this).data('customEventRanAlready') != 1){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).data('customEventRanAlready', 1);
}
})
Like Kevin mentioned, you can accomplish this by manipulating the CSS selectors, but you actually don't have to use :not(). Here's an alternative method:
// Use an attribute selector like so. This will only select elements
// that have 'theImage' as their ONLY class. Adding another class to them
// will effectively disable the repeating calls from live()
$('div[class=theImage]').live('inview',function(event, visible, visiblePartX, visiblePartY) {
if (visiblePartY=="top") {
$(this).animate({ opacity: 1 });
$(this).addClass('nolive');
console.log("look just how many times this is firing")
}
});
I used the actual code from your site. Hope that was okay.

Resources