Button CreateJs - createjs

Can anyone help me. CanĀ“t make this button work... I used something similar before. I call this GameMenu as a scene inside another JS.
var scene = new game.GameMenu();
scene.on(game.GameStateEvents.GAME, this.onStateEvent, this, true, {state:game.GameStates.GAME});
stage.addChild(scene);
The button is here inside this code:
(function (window) {
window.game = window.game || {}
function GameMenu() {
this.initialize();
}
var p = GameMenu.prototype = new createjs.Container();
p.btnIniciar;
p.Container_initialize = p.initialize;
p.initialize = function () {
this.Container_initialize();
this.addTitle();
this.addButton();
}
p.addTitle = function () {
var titulo = new createjs.Sprite(spritesheet, 'titulo');
titulo.x = screen_width / 2 - titulo.getBounds().width/2;
titulo.y = screen_height / 2 - titulo.getBounds().height/2;
this.addChild(titulo);
}
p.addButton = function() {
this.btnIniciar = new createjs.Sprite(spritesheet, 'btnIniciar');
this.btnIniciar.mouseEnabled = true;
this.btnIniciar.cursor = 'pointer';
this.btnIniciar.x = screen_width / 2 - this.btnIniciar.getBounds().width/2;
this.btnIniciar.y = (screen_height / 2 - this.btnIniciar.getBounds().height/2) + 200;
stage.addChild(this.btnIniciar);
this.btnIniciar.addEventListener("click", function(event) {
console.log("Click not working");
});
}
window.game.GameMenu = GameMenu;
}(window));

Related

Backbone - Test method in view that uses ReadFile

I have written a backbone view which takes a file object or blob as an option in instantiation and then checks that file for EXIF data, corrects orientation and resizes the image if necessary depending on the options passed in.
Within the view there is a function mainFn which takes the file object and calls all other subsequent functions.
My issue is how to I test mainFn that uses ReadFile and an image constructor?
For my test set-up I am using mocah, chai, sinon and phantomjs.
In my sample code I have removed all other functions as to not add unnecessary clutter. If you wish to see the whole view visit its github repository.
var imageUpLoad = Backbone.View.extend({
template: _.template(document.getElementById("file-uploader-template").innerHTML),
// global variables passed in through options - required
_file: null, // our target file
cb: null,
maxFileSize: null, // megabytes
maxHeight: null, // pixels - resize target
maxWidth: null, // pixels - resize target
minWidth: null, // pixels
maxAllowedHeight: null, //pixels
maxAllowedWidth: null, // pixels
// globals determined through function
sourceWidth: null,
sourceHeight: null,
initialize: function (options) {
this._file = options.file;
this.cb = options.cb;
this.maxHeight = options.maxHeight;
this.maxWidth = options.maxWidth;
this.maxFileSize = options.maxFileSize;
this.minWidth = options.minWidth;
this.maxAllowedHeight = options.maxAllowedHeight;
this.maxAllowedWidth = options.maxAllowedWidth;
},
render: function () {
this.setElement(this.template());
this.mainFn(this._file);
return this;
},
// returns the width and height of the source file and calls the transform function
mainFn: function (file) {
var fr = new FileReader();
var that = this;
fr.onloadend = function () {
var _img = new Image();
// image width and height can only be determined once the image has loaded
_img.onload = function () {
that.sourceWidth = _img.width;
that.sourceHeight = _img.height;
that.transformImg(file);
};
_img.src = fr.result;
};
fr.readAsDataURL(file);
}
});
My test set-up
describe("image-upload view", function () {
before(function () {
// create test fixture
this.$fixture = $('<div id="image-view-fixture"></div><div>');
});
beforeEach(function () {
// fake image
this.b64DataJPG = '/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAA' +
'ABABIBAwABAAAABgASAAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEB' +
'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ' +
'EBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB' +
'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ' +
'EBAQEBAQH/wAARCAABAAIDASIAAhEBAxEB/8QAHwAAAQUBAQEB' +
'AQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBA' +
'QAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAk' +
'M2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1' +
'hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKj' +
'pKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+' +
'Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAA' +
'AAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAx' +
'EEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl' +
'8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2' +
'hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmq' +
'srO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8v' +
'P09fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigD/2Q==';
var b64toBlob = function (b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var input = b64Data.replace(/\s/g, '');
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
try{
var blob = new Blob( byteArrays, {type : contentType});
}
catch(e){
// TypeError old chrome and FF
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if(e.name == 'TypeError' && window.BlobBuilder){
var bb = new BlobBuilder();
bb.append(byteArrays);
blob = bb.getBlob(contentType);
}
else if(e.name == "InvalidStateError"){
// InvalidStateError (tested on FF13 WinXP)
blob = new Blob(byteArrays, {type : contentType});
}
else{
// We're screwed, blob constructor unsupported entirely
}
}
return blob;
};
this.blobJPG = b64toBlob(this.b64DataJPG, "image/jpg");
/* **************** */
this.$fixture.empty().appendTo($("#fixtures"));
this.view = new imageUpLoad({
file: this.blobJPG,
cb: function (url) {console.log(url);},
maxFileSize: 500000,
minWidth: 200,
maxHeight: 900,
maxWidth: 1000,
maxAllowedHeight: 4300,
maxAllowedWidth: 1000
});
this.renderSpy = sinon.spy(this.view, "render");
this.readFileDataStub = sinon.stub(this.view, 'readFileData');
this.resizeImageStub = sinon.stub(this.view, 'resizeImage');
this.returnDataUrlStub = sinon.stub(this.view, 'returnDataUrl');
this.mainFnSpy = sinon.spy(this.view, 'mainFn');
this.transformImgStub = sinon.stub(this.view, 'transformImg');
this.sizeConfigStub = sinon.stub(this.view, 'sizeConfig');
this.resizeConfStub = sinon.stub(this.view, 'resizeConf');
this.callbackSpy = sinon.spy();
});
afterEach(function () {
this.renderSpy.restore();
this.readFileDataStub.restore();
this.resizeImageStub.restore();
this.returnDataUrlStub.restore();
this.mainFnSpy.restore();
this.sizeConfigStub.restore();
this.resizeConfStub.restore();
this.transformImgStub.restore();
});
after(function () {
$("#fixtures").empty();
});
it("can render", function () {
var _view = this.view.render();
expect(this.renderSpy).to.have.been.called;
expect(this.view).to.equal(_view);
});
});
You could either mock the FileReader / Image on the window, e.g.
// beforeEach
var _FileReader = window.FileReader;
window.FileReader = sinon.stub().return('whatever');
// afterEach
window.FileReader = _FileReader;
Or reference the constructor on the instance, e.g.
// view.js
var View = Backbone.View.extend({
FileReader: window.FileReader,
mainFn: function() {
var fileReader = new this.FileReader();
}
});
// view.spec.js
sinon.stub(this.view, 'FileReader').return('whatever');
Personally I'd prefer the latter as there's no risk of breaking the global reference if, for example, you forget to reassign the original value.

how to add button to reduce and to increase the spped of interval in action script 2.0

I have a code with which i can fetch image through internet ... I have completed it. I have to add to button , one to increase and one to reduce the interval ... in action script 2.0
import mx.transitions.*;
import mx.transitions.easing.*;
my_pb.mode = "manual";
this.createEmptyMovieClip("img_mc", 999);
var my_mcl:MovieClipLoader = new MovieClipLoader();
var mclListenerbject = new Object();
mclListener.onLoadStart = function(target_mc:MovieClip) {
my_pb.label = "loading: "+target_mc._name;
};
mclListener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number) {
var pctLoaded:Number = Math.ceil(100*(numBytesLoaded/numBytesTotal));
my_pb.setProgress(numBytesLoaded, numBytesTotal);
};
var number:Number = 2000;
var myInterval = setInterval(testInterval, number); //
function testInterval() {
my_mcl.addListener(mclListener);
my_mcl.loadClip("http://google.com/l5", img_mc);
}
i can create 2 button but there are some error...
If you want change the interval of the setInterval function, you have to clear it and then use the function with the new interval value, like this :
var delay:Number = 2000;
var interval = setInterval(on_repeat, delay);
function on_repeat() {
// instructions
}
fast.onPress = function(){
clearInterval(interval);
interval = setInterval(on_repeat, delay - 1000);
}
slow.onPress = function(){
clearInterval(interval);
interval = setInterval(on_repeat, delay + 1000);
}
But, as #Raptor has said, I recommend you to use ActionScript 3 instead of the old ActionScript 2.
For example, the code above can simply be replaced by a Timer object like this :
var delay:int = 2000;
var timer:Timer = new Timer(delay);
timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void {
// instructions
})
timer.start();
fast.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
timer.delay = delay - 1000;
})
slow.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
timer.delay = delay + 1000;
})
Hope that can help.
var current_loader:Number = 1;
var current_img:Number = 0;
this.createEmptyMovieClip('img_01', 999);
this.createEmptyMovieClip('img_02', 998);
img_01._x = img_01._y=img_02._x=img_02._y=20;
var loader:MovieClipLoader = new MovieClipLoader();
var listener:Object = new Object();
listener.onLoadStart = function(target_mc:MovieClip) {
};
listener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number) {
};
listener.onLoadComplete = function(target_mc:MovieClip) {
if (target_mc._name == 'img_01') {
img_02._visible = false;
} else {
img_01._visible = false;
}
};
var delay:Number = 2000;
var interval = setInterval(load_image, delay);
function load_image() {
loader.addListener(listener);
loader.loadClip("http://google.com/latimage.php?", _root['img_0'+current_loader]);
current_loader = current_loader == 1 ? 2 : 1;
current_img = current_img == images.length-1 ? 0 : current_img+1;
}
slow.onRelease = function() {
interval = setInterval(load_image, delay+1000);
trace(interval);
};
fast.onRelease = function() {
clearInterval(interval);
interval = setInterval(load_image, delay-1000);
trace(interval);
};
image_load();

How to get e.globalPoint in Titanium 3.1.0 GA

I am trying to get globalPoint in Titanium iPhone application when touchmove event occur, I use following code to get globalPoint
var x = parseInt(e.globalPoint.x, 10);
It work fine until I updated Titanium 3.0.2 GA to 3.1.0 GA, after updating I run the application I got following error
'undefined' is not an object (evaluating 'e.globalPoint.x')
I am using this code for swiping window
var animateLeft = Ti.UI.createAnimation({
left : 250,
curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
duration : 150
});
var animateRight = Ti.UI.createAnimation({
left : 0,
curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
duration : 150
});
var touchStartX = 0;
var touchStarted = false;
$.innerwin.addEventListener('touchstart', function(e) {
touchStartX = parseInt(e.x, 10);
});
$.innerwin.addEventListener('touchend', function(e) {
touchStarted = false;
if ($.win.left >= 150) {
$.win.animate(animateLeft);
hasSlided = true;
} else {
$.win.animate(animateRight);
hasSlided = false;
}
});
$.innerwin.addEventListener('touchmove', function(e) {
var x = parseInt(e.globalPoint.x, 10);
var newLeft = x - touchStartX;
if (touchStarted) {
if (newLeft <= 250 && newLeft >= 0) {
$.win.left = newLeft;
}
}
if (newLeft > 30) {
touchStarted = true;
}
});
$.button.addEventListener('singletap', function(e) {
$.toggleSlider();
});
var hasSlided = false;
exports.toggleSlider = function() {
if (!hasSlided) {
$.win.animate(animateLeft);
hasSlided = true;
} else {
$.win.animate(animateRight);
hasSlided = false;
}
}
This has been deprecated:
Instead you need to do this (in this very contrived example), and use the convertPointToView method:
var baseview = Ti.UI.createView({width : Ti.UI.FILL, height : Ti.UI.FILL});
var view = Ti.UI.createView({ width : 20, height : 20 });
view.addEventListener('touchmove', function(e) {
var globalPoint = convertPointToView({x : e.x, y : e.y}, baseview);
});
Finally, I used following widget
http://www.danielsefton.com/2013/05/slider-menu-widget-v2-for-titanium-alloy/

how to to process result of google distance matrix api further?

i am new to programming.. i have this code which gives distance between two points but need to further multiply it by an integer say 10.. the project i am working on is abt calculating distance between two points and multiplying it with fare/Km like Rs.10/km (Indian Rupees) for the same. So if the distance is 30 km the fare would be 30*10 = Rs.300
Thanks in advance
following is the code
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = '';
var destinationA = '';
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
var fromText = document.getElementById('FAdd');
var options = {
componentRestrictions: {country: 'in'}
};var fromAuto = new google.maps.places.Autocomplete(fromText, options);
fromAuto.bindTo('bound', map);
var toText = document.getElementById('TAdd');
var toAuto = new google.maps.places.Autocomplete(toText, options);
toAuto.bindTo('bound', map);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [document.getElementById("FAdd").value],
destinations: [document.getElementById("TAdd").value],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += results[j].distance.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
I use an Ajax call to PHP, and haven't yet used getDistanceMatrix(), but this should be an easy fix.
First, if you know you will always only have one origin and one destination, you don't need the "for" loop in your callback function. Second, you're taking the distance text rather than the distance value.
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
[...]
} else {
deleteOverlays();
var outputDiv = document.getElementById('outputDiv'),
origin = response.originAddresses[0],
destination = response.destinationAddresses[0],
result = response.rows[0].elements[0],
distance = result.distance.value,
text = result.distance.text,
price = 10 * distance;
outputDiv.innerHTML = '<p>' + text + ': Rs.' + price + '</p>';
addMarker(origin, false);
addMarker(destination, false);
}
}
I haven't tested this, so it probably needs to be tweaked. ( See https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixResponses )

Corrupt Windows in Titanium

I open windows as follows:
app.js:
var NavigationController = require('NavigationController').NavigationController,
TestWindow = require('main_windows/tmain').TestWindow;
//create NavigationController which will drive our simple application
var controller = new NavigationController();
//open initial window
controller.open(new TestWindow(controller));
function openWindow(name, naController, event) {
var TestWindow2 = require('main_windows/t' + name).TestWindow;
var win = Titanium.UI.currentWindow;
var swin = Titanium.UI.createWindow();
if(event.bid)
swin.bid = event.bid;
if(event.uniq)
swin.uniq = event.uniq;
if (event.zipcode)
swin.zipcode = event.zipcode;
if (event.user_id)
swin.user_id = event.user_id;
if (event.service_id)
swin.service_id = event.service_id;
if (event.service_name)
swin.service_name = event.service_name;
if (event.user_uniqid)
swin.user_uniqid = event.user_uniqid;
if (event.user_name)
swin.user_name = event.user_name;
if (event.user_email)
swin.user_email = event.user_email;
if (event.provider_id)
swin.provider_id = event.provider_id;
if (event.provider_name)
swin.provider_name = event.provider_name;
if (event.total)
swin.total = event.total;
if(event.response)
swin.response = event.response;
swin.backgroundColor = '#f7f7f7';
swin.barImage = 'images/example.gif';
naController.open(new TestWindow2(naController, swin));
}
Here is the NavigationController.js
exports.NavigationController = function() {
this.windowStack = [];
};
exports.NavigationController.prototype.open = function(/*Ti.UI.Window*/windowToOpen) {
//add the window to the stack of windows managed by the controller
this.windowStack.push(windowToOpen);
//alert('open' + this.windowStack.length);
//grab a copy of the current nav controller for use in the callback
var that = this;
windowToOpen.addEventListener('close', function() {
// alert('open' + that.windowStack.length);
if(that.windowStack.length > 1)
{
//alert('pop' + that.windowStack.length);
that.windowStack.pop();
}
});
//hack - setting this property ensures the window is "heavyweight" (associated with an Android activity)
windowToOpen.navBarHidden = windowToOpen.navBarHidden || false;
//This is the first window
if(this.windowStack.length === 1) {
if(Ti.Platform.osname === 'android') {
windowToOpen.exitOnClose = true;
windowToOpen.open();
} else {
//alert('nav' + this.windowStack.length);
this.navGroup = Ti.UI.iPhone.createNavigationGroup({
window : windowToOpen
});
var containerWindow = Ti.UI.createWindow();
containerWindow.add(this.navGroup);
containerWindow.open();
}
}
//All subsequent windows
else {
if(Ti.Platform.osname === 'android') {
windowToOpen.open();
} else {
//alert('nav2' + this.windowStack.length);
this.navGroup.open(windowToOpen);
}
}
};
//go back to the initial window of the NavigationController
exports.NavigationController.prototype.home = function() {
//store a copy of all the current windows on the stack
//alert('reset' + this.windowStack.length);
var windows = this.windowStack.concat([]);
for(var i = 1, l = windows.length; i < l; i++) {
(this.navGroup) ? this.navGroup.close(windows[i]) : windows[i].close();
}
this.windowStack = [this.windowStack[0]]; //reset stack
//alert('n' + this.windowStack.length);
};
Here is tmain.js
exports.TestWindow = function(navController) {
var win = Ti.UI.createWindow({
backButtonTitleImage : 'images/backb.gif',
fullscreen : false,
navBarHidden : true,
});
var t1 = null;
win.backgroundImage = 'images/back.jpg';
var view = Titanium.UI.createView({
width : '100%',
height : '100%',
top : 270,
layout : 'vertical'
});
var b3 = Titanium.UI.createImageView({
url : 'images/login.gif',
height : 80
});
view.add(b3);
var b4 = Titanium.UI.createImageView({
url : 'images/signup.gif',
top : 0,
height : 80
});
view.add(b4);
win.add(view);
var list1 = function(e) {
openWindow('login', navController, e);
};
b3.addEventListener('click', list1);
var list2 = function(e) {
openWindow('register', navController, e);
};
b4.addEventListener('click', list2);
win.addEventListener('close', function (e) {
alert(3);
b3.removeEventListener('click', list1);
b4.removeEventListener('click', list2);
});
return win;
};
So I use the openWindow function to open windows in the app. I have a logout botton, that when people click on it, calls the function navController.home() (see Navigation Controller), but the problem is clicking on the logout link causes corrupt window state - meaning that the application crashes and when you try to open it, windows are mixed together (like buttons in window 3 show up in window 2).
What am I doing wrong?