Is it possible to pause/resume/manipulate a swiffyobject from JS? - javascript

There seems to be little support or discussion around regarding Google Swiffy (http://swiffy.googlelabs.com/).
Is it possible to effectively pause/resume/manipulate a swiffyobject from JS?
Using standard Google output, I noticed the swiffyobject could be found in console with a few properties; notably frameRate. Could this property be manipulated for example?

For the latest Swiffy release (Swiffy runtime version 5.2 https://www.gstatic.com/swiffy/v5.2/runtime.js) I did this.
1.Use jsbeautifier.org as mentioned in samb's post.
2.Find the function containing .start(). In my case...
db(N, function () {
var a = this.Dg;
this.ck(function () {
a.start()
})
});
db(Yj[I], Yj[I].start);
3.Duplicate this function with a different name, and replace start() with stop()
myNewFunction(N, function () {
var a = this.Dg;
this.ck(function () {
a.stop()
})
});
myNewFunction(Yj[I], Yj[I].stop);
4.Find the declaration of the function containing .start(). In my case db.
function db(a, b) {
return a.start = b
}
5.Duplicate this function and call it the same as the new function you created with stop() in and replace start with stop. In my case myNewFunction.
function myNewFunction(a, b) {
return a.stop = b
}
That's it.
Now you can call my anim.stop();
e.g.
//create anim
var anim = {swiffy code};
var myAnim = new swiffy.Stage(document.getElementById('animContainer'), anim);
myAnim.start();
//some button click
myButton.on('click',function(){
myAnim.stop();
});

Sorry for my english I'm french;)
I was looking for a solution to be able to properly handle animation Swiffy.
Since the new version (5.0) google code has changed and I can no longer maniupler animation with small hacks found on the net ...
For cons, I coded force to find a solution .. which seems to me very simple and clean .. (without touching the source Swiffy!)
In fact any part of this post : swiffy / javascript
Can be recovered with flashvars Swiffy (in as2 and as3 it should work too ..)
the side javascript can do this kind of things:
function playMovie(){
stage.setFlashVars('myresponse=play');
return false;
}
function stopMovie(){
stage.setFlashVars('myresponse=pause');
return false;
}
and the side of the flash in a function enterFrame ... :
_root.onEnterFrame = function(){
switch(_level0.myresponse){
case 'play':
_root.play();
break;
case 'pause':
_root.stop();
break;
default :
break;
}
_level0.myresponse = undefined;
}
and that's it!
To you organize the methods you want but .. it works;)
Must retake the undefined variable if you want to reuse it later ;)

Having un-minified the runtime.js - it was possible to achieve the behaviour I wanted.
On line 3312 (unminified - jsbeautifier.org)
M.start = function (arg) {
this.T[Qa]();
if(arg){
this.cb.start(arg)
}else{
this.cb.start()
}
};
And on line 3823:
M.start = function(arg) {
if(arg){
console.log(arg);
window.clearInterval(window.pauseAnimation)
}else{
window.pauseAnimation = window.setInterval(Ob(this.ne, this), 40 );
if (!this.ie) this.ie = !0, this.ne(), window.pauseAnimation
}
};
Then using console, it is possible to pause/resume your animation using:
stage.start(true) // PAUSE the animation.
stage.start() // RESUME the animation.

Related

Javascript prototype function override when x

In my case, I'm using the Phaser framework.
So in this example I'm extending the Group class of phaser. Every 'actor' class (Sprite, Group, ...) calls upon the update() prototype every few miliseconds.
My idea was to extend this function only when the application runs on a desktop (so not on a phone).
for example:
var MousePointer = function (game, parent, name) {
Phaser.Group.call(this, game, parent, name);
this.init();
};
MousePointer.prototype = Object.create(Phaser.Group.prototype);
MousePointer.prototype.constructor = MousePointer;
MousePointer.prototype.init = function () {
// ... init
};
MousePointer.prototype.update = function () {
// Do something when on desktop
};
I can't possibly use an if clausule in the update() function to check whether the player is on dekstop/tablet/phone. So is there a way to actually override the prototype on initialisation?
for example (pseudocode):
if(onPhone)
MousePointer.prototype.update = parent.prototype.update;
else
MousePointer.prototype.update = this.update;
Well, you've kind of already written the answer for yourself, haven't you? This code (not inside the init method).
if(onPhone) {
MousePointer.prototype.update = function(){//Phone implementation};
} else {
MousePointer.prototype.update = function(){//Other implementation};
}
I advise against starting off with the "regular" function and then potentially overriding it, since you're just declaring it for nothing.
I think a better way to do this would be to write two different classes that shares the same parent, and then write different update() implementations for them. Then you can just do something like:
if(phone) {
var obj = new PhoneMousePointerObject();
} else {
var obj = new DesktopMousePointerObject();
}
// ... later
obj.update()

JavaScript Too much recursion error with facebook JavaScript SDK

i am sending FB.login request to facebook. but FB is not defined while javascript SDK is still loading core javascript resources.
so, i put a check to get FB variable
function check_FB_variable(){
if(typeof FB=='undefined'){
check_FB_variable();
}else{}
}
check_FB_variable();
But this approach gives me Too much recursion error.
so , i put this code as
function check_FB_variable(){
if(typeof FB=='undefined'){
setTimeout(check_FB_variable,600);
}else{}
}
check_FB_variable();
but in this approach the before timeout function make a call function moves down and gives error
FB.login not defined.
please, help.
I've used something similar to check if JQMobi exists, I don't know exactly why but I think the exception is thrown because you call the pointer to the function every time.
You should try checking in an interval like this (Untested):
var facebookChecker = window.setInterval(fbCheck, 200);
var fbCheck = function () {
if (typeof FB != 'undefined' && facebookChecker != null) {
window.clearInterval(facebookChecker);
facebookChecker = null;
// Whatever you want to do if facebook is loaded
// Example: InitFBLogin();
}
}
Or you could use a while statement (the one I used):
/*
* This JQ Fix tries to attach Jquery to a variable to ensure it exists.
* - Marvin Brouwer.
*/
var FixJQ = function () {
var JQFIX = null;
while (!JQFIX || JQFIX == null) {
try {
JQFIX = jQuery;
} catch (nothing) { jQuery = $; };
};
JQFIX = null;
return true;
};
if (FixJQ()) {
FixJQ = null;
};
The beauty of the last one is that you can put you next step below this, because it will wait until the while loop has finished.
I honestly do not know which one is better/faster but I’m sure the bottom one will work.

how to write test cases for simple calculator application in js

I am a front end developer trying to learn Test driven development. I've built a simple js calculator using jQuery/jasmine.
From what I learned I started writing my test cases first (in jasmine).
describe("calculator", function() {
it("add correctly", function() {
expect(add(2,3)).toEqual(5);
});
it("subtract correctly", function() {
expect(sub(2,3)).toEqual(-1);
});
describe("divide", function(){
it("divided correctly", function(){
expect (divide(2,3)).toEqual(0.6666666666666666);
});
it("divided by 0 gives infite", function(){
expect (divide(2,0)).toEqual(Infinity);
});
});
describe("toggle sign", function(){
it("toggle to - sign", function() {
expect (toggleSign(2)).toEqual(-2);
});
it("toggle to + sign", function() {
expect (toggleSign(-2)).toEqual(2);
});
});
});
then pass them with minimal code
(function(window, document, undefined){ "use strict";
window.add = function(a,b){ return a+b; };
window.sub = function(a,b){ return a-b; };
window.divide =function(a,b){ return (a/b); };
window.toggleSign = function(a){ return -a; };
}(window, document));
I was all happy and content until I actually started building the app
Here is what it looks like
http://niteshsharma.com/jscalc/
The most sensible way I could come up with, to write a calculator, is to create a simple string of the complete operation and eval it on execution
window.press = function(a){
$("#display").html(function(i, oldHtml){
return oldHtml+a;
});
};
window.execute= function(){
try{
$("#display").html( new Function( "return " + $("#display").html())() );
}
catch(err){
alert("error");
}
};
How could I write a test case for such code?
If some one could explain to me the correct process of doing TDD (with my example of the calculator) I would appreciate it a lot.
Here's your answer. Via jQuery, you can dynamically add your "display" element to the page, and then execute your press and execute functions and do assertions based on the contents of the display element. Here's some tests.
describe("press", function(){
it("add-remove display element", function(){
// Dynamically add a span element with id="display"
$('body').append($('<span id="display">').text('0'));
expect($('#display').length).toEqual(1);
// Clean up after yourself here - tests should be atomic
$('#display').remove();
expect($('#display').length).toEqual(0);
});
it("add-remove display element", function(){
$('body').append($('<span id="display">').text('0'));
// With the display element present, run the press function
press('2');
expect($('#display').html()).toEqual('02');
$('#display').remove();
});
});
describe("execute", function(){
it("execute a couple presses and run a calculation", function(){
$('body').append($('<span id="display">').text('0'));
// With the display element present, run the press function
press('2');
press('+');
press('3');
execute();
expect($('#display').html()).toEqual('5');
$('#display').remove();
});
});
If I may suggest as well, it's not a good idea to add your calculator functions to the window object. You could do something like this perhaps (untested stub code):
function Calculator(){
// Private members
var firstNumber = 0;
var secondNumber = 0;
function toggleSign(){}
// Public members
return {
press: function(){},
execute: function(){}
};
}
// To use it, instatiate a new calculator and call its public methods
var calc = new Calculator();
calc.press('2');
calc.press('+');
calc.press('3');
calc.execute();
Also, you should avoid executing strings like you're doing in your execute method... Inside your Calculator class, you should have private variables to store the first number and second number, and then just do math on them without having to execute strings.
Hope this helps.
Andy

Spinlock in Javascript

How can I do a spinlock in javascript?
I'm trying to load a bunch of images and I can only move forward after everything is loaded, so I have a spinlock like
for(...)
image[i].onload = function() { ++imagesloaded; }
while(imagesloaded != totalimages)
{
}
And it crashes my browser. Is there a better way to do it? Or a yield / sleep function I'm missing?
Short answer: don't spinlock.
Longer answer: here's how to do it:
var imagesLoaded = 0;
var totalImages = 42;
function handleImageLoad()
{
imagesLoaded++;
if (imagesLoaded === totalImages)
{
doSomething();
}
}
for (var i=0; i<totalImages; i++)
{
image[i].onload = handleImageLoad;
}
In general, when you want to sleep/wait/spin in JavaScript, instead think about solving the problem in terms of callbacks (and setTimeout/setInterval).
The answers above aren't useful as spinlocks may be required because of limitations/bugs in browsers. For instance safari (hopefully not future versions) requires the use of method window.open when you want to generate a file in javascript. The consequence of this is that you cannot generate the file using any callbacks (because of popup blockers), this in effect forces the use of a dialog window that first calls the file generation function (using callbacks) and then a button that downloads the file. Because spinlocks don't work the code becomes the following:
function process(callback) {
processCallbackData = null; // global var that must be a unique name
callback(function(data) {
processCallbackData = data;
});
}
function fowardButton() {
if(processCallbackData!=null) {
goForwardUsingCallbackIncompatibleCode();
} else {
displayStillLoadingWarning();
}
}
Don't use a loop to check. Check in the event handler function. (So you only do the check when an image has loaded, not continuously and as quickly as possible)

How should I implement OOP patterns to interactive web applications (with the aide of jQuery)?

Sometimes, using jQuery induces you to abuse its power (at least for me because of its selector matching capability). Event handlers here and there. Utility functions here and everywhere. Code coherence can almost seem nonexistent. I want to alleviate that problem by implementing OOP patterns, but since I have C++ and python background, implementing it in javascript is weirding me out a little bit.
The code below uses OOP patterns, but I'm not entirely sure if my implementations are good practices. The reason I'm doubting my implementations is because of the 3rd comment in my last stackoverflow question. I know it's only one certain detail in my code he commented on, but it also makes me wonder about the other patterns I'm implementing in my code.
I would really appreciate if you could point out the flaws and pitfalls in my patterns and/or if you have any suggestions. Many thanks in advance.
(this code is an simplification of something I'm developing, but the idea is similar)
Live Example
$(function(){
var stream = new Stream();
});
/* Stream Class
------------------------------------------*/
function Stream(){
// Disables multiple Stream objects
if (this.singleton)
return
else
this.__proto__.singleton = true;
this.elements = jQueryMapping(this.selectors) // Converts a map of selectors to a map of jQuery objects
this.initEvents();
}
Stream.prototype.singleton = false;
Stream.prototype.selectors = {
stream : '#stream',
post_content : '#post-content',
add_post: '#add-post',
// ... more action selectors
}
Stream.prototype.initEvents = function(){
this.elements.add_post.click(this, this.addPost);
// ... more action event-listeners
}
Stream.prototype.addPost = function(e){
var self = e.data;
var post_content = self.elements.post_content.val();
if (post_content)
self.elements.stream.append(new Post(post_content));
}
/* Post Class
------------------------------------------*/
function Post(post_content){
this.$element = $('<li>')
.text(post_content)
.append('<button class="delete-post">Delete</button>');
this.elements = jQueryMapping(this.selectors, this.$element);
this.initEvents();
return this.$element;
}
Post.prototype.selectors = {
delete_post: 'button.delete-post',
// ... more action selectors
}
Post.prototype.initEvents = function(){
this.elements.delete_post.click(this.deletePost);
// ... more action event-listeners
}
Post.prototype.deletePost = function(){
$(this).parent().slideUp();
}
/* Utils
------------------------------------------*/
function jQueryMapping(map, context){
// Converts a map of selectors to a map of jQuery objects
var $map = {};
$.each(map, function(key, value){
$map[key] = (context) ? $(value, context) : $(value);
});
return $map;
}
I believe your code is over engineered. I've re factored and it simplified it as can be seen here. If you really want a heavy OOP setup I recommend you use a clientside MVC (Backbone, knockout, etc) construct to do it properly or keep it light instead.
I'll proceed with general feedback on your code.
/* Stream Class
------------------------------------------*/
function Stream(){
// Disables multiple Stream objects
if (this.singleton)
return
else
this.__proto__.singleton = true;
this.elements = jQueryMapping(this.selectors) // Converts a map of selectors to a map of jQuery objects
this.initEvents();
}
There is no reason to use a singleton like this. It's also very bad to use .__proto__
I would recommend pattern like this instead.
var Stream = (function() {
var Stream = function() { ... };
// prototype stuff
var stream = new Stream();
return function() {
return stream;
};
})());
Storing a hash of data like that on the prototype is unneccesary.
Stream.prototype.selectors = {
stream : '#stream',
post_content : '#post-content',
add_post: '#add-post',
// ... more action selectors
}
You can include this as a defaults hash instead.
(function() {
var defaults = {
stream : '#stream',
post_content : '#post-content',
add_post: '#add-post',
// ... more action selectors
}
function Stream() {
...
this.elements = jQueryMapping(defaults);
}
}());
Your utility function could be optimised slightly.
$map[key] = (context) ? $(value, context) : $(value);
This could be rewritten as
$map[key] = $(value, context)
Since if context is undefined you just pass in an undefined paramater which is the same as passing in no parameter.
The title of this reads "for beginners", but I've found this section on design patterns, and this section on design patterns using jQuery useful.

Categories

Resources