Titanium not running function upon click - titanium

I am reading through titanium best practises and i was wondering why this doesnt appear to work can some one tell me whats changed with the api?
https://wiki.appcelerator.org/display/guides/Mobile+Best+Practices
ui/ToggleBox.js - A custom check box
function ToggleBox(onChange) {
this.view = Ti.UI.createView({backgroundColor:'red',height:50,width:50});
//private instance variable
var active = false;
//public instance functions to update internal state, execute events
this.setActive = function(_active) {
active = _active;
this.view.backgroundColor = (active) ? 'green' : 'red';
onChange.call(instance);
};
this.isActive = function() {
return active;
};
//set up behavior for component
this.view.addEventListener('click', function() {
this.setActive(!active);
});
}
exports.ToggleBox = ToggleBox;
Sample usage in app.js
var win = Ti.UI.createWindow({backgroundColor:'white'});
var ToggleBox = require('ui/ToggleBox').ToggleBox;
var tb = new ToggleBox(function() {
alert('The check box is currently: '+this.isActive());
});
tb.view.top = 50;
tb.view.left = 100;
win.add(tb.view);
it doesn't seem to want to return the setActive method when called from the add event listener?

The "this" in your click listener isn't what you're expecting it to be. (It's probably the view.) Because your function is already the ToggleBox context, the easiest solution is to just use a direct reference to setActive. "this." is only necessary for the API you're exposing for other code.
function ToggleBox(onChange) {
var view = this.view = Ti.UI.createView({backgroundColor:'red',height:50,width:50});
//private instance variable
var active = false;
//public instance functions to update internal state, execute events
var setActive = this.setActive = function(_active) {
active = _active;
view.backgroundColor = (active) ? 'green' : 'red';
onChange.call(instance);
};
var isActive = this.isActive = function() {
return active;
};
//set up behavior for component
view.addEventListener('click', function() {
setActive(!active);
});
}
exports.ToggleBox = ToggleBox;

Related

Global Variables only Called Once then Lost their Scope

I Have a Problem with my Script and hope helping me, and thanks in advance, i still learning javascript and try to learn somthing new everyday, i have a script that draw modeless interface (palette) and have button including (option) that make another new palette (for options), i made the variables as globals for the option palette, but the problem is the global variables is only called once!, and the script lose the global variable scope!.
enter image description here
so my question is how to make the variables not losing its scope and retain in the memory? as long the script run, as an Example if the user move the slider and hit (Show alert due options) its only run once and then lose the scope, even the slider no longer interact with the user and update text box, please test the code to see the problem, and thank again for any help or advice.
Best
M.Hasanain
//Global Variables only Called Once then Lost their Scope!
#targetengine "session1";
var w = new Window("palette", {independent:true}); //Main Palette Windows
var findoptions = new Window("palette"); //Options Palette
function Main() {
// Check to see whether any InDesign documents are open.
// If no documents are open, display an error message.
if (app.documents.length > 0) {
var myDoc = app.activeDocument;
}else{
// No documents are open, so display an error message.
alert("No InDesign documents are open. Please open a document and try again.");
}
}
//---------------------------------------------------------
//Making Palettes Windows
//---------------------------------------------------------
#targetengine "session1";
var w = new Window("palette", {independent:true}); //Main Palette Windows
var findoptions = new Window("palette"); //Options Palette
//gqmanager is the (GREP Query Manager) outside the main Function
w.text = "Test the Connection Between Global Variables and Palettes";
w.preferredSize.width = 500;
w.alignChildren = ["center", "center"]; //"left";
w.orientation = "column"; //"row";
w.spacing = 10;
w.margins = 16;
//Parent - Input Panel Prepare
var InputPanel = w.add("panel", undefined, undefined, { name: "panel1" });
InputPanel.text = "Text Find : ";
InputPanel.preferredSize.width = 1000;
InputPanel.orientation = "row";
InputPanel.alignChildren = ["center", "center"];
InputPanel.spacing = 10;
InputPanel.margins = 16;
//Children - input Panel Inside Prepare
var myInputPanelInside = InputPanel.add("group", undefined, { name: "myInput" });
//--Adding Find What
myInputPanelInside.add("statictext", undefined, "Find What :");
//myInputPanelInside.alignment = "center";
var myGREPString = myInputPanelInside.add("edittext", undefined, "SAMPLE");
myGREPString.helpTip = "Enter Your Text"
myGREPString.characters = 20;
myGREPString.enabled = true;
myGREPString.preferredSize.width = 460;
var Button1 = myInputPanelInside.add("button", undefined, "Options");
//Parent - Radio Panel Prepare
var RadioPanel = w.add("panel", undefined, undefined, { name: "panel2" });
RadioPanel.text = "Select Desired Option : ";
RadioPanel.preferredSize.width = 1000;
RadioPanel.orientation = "row";
RadioPanel.alignChildren = ["center", "center"];
RadioPanel.spacing = 10;
RadioPanel.margins = 16;
//Children - input Panel Inside Prepare
var myRadioPanelInside = RadioPanel.add("group", undefined, { name: "myRadio" });
myRadioPanelInside.preferredSize.width = 500;
myRadioPanelInside.alignChildren = ["center", "center"];
//Adding Radio Buttons
var radio1 = myRadioPanelInside.add("radiobutton", undefined, "Option 1");
var radio2 = myRadioPanelInside.add("radiobutton", undefined, "Option 2");
var radio3 = myRadioPanelInside.add("radiobutton", undefined, "Option 3");
radio1.preferredSize.width = 200;
radio2.preferredSize.width = 200;
radio3.preferredSize.width = 200;
//Previous Default Condition
radio1.value = true;
var myButtonGroup = w.add("group");
myButtonGroup.alignment = "center";
var Button2 = myButtonGroup.add("button", undefined, "Show Alert Due Options");
var Button3 = myButtonGroup.add("button", undefined, "Exit");
Button1.onClick = function () {
CalltheFindOptions();
}
Button2.onClick = function () { Find(); };
function Find() {
doRadioButtonOpt();
}
Button3.onClick = function() {Canceled();};
function Canceled() {
ExitSure();
}
//After Drawing Interface
var a = w.show();
function ExitSure() {
var a = w.close();
exit(0);
}
//User Selection for Radio Buttons
function doRadioButtonOpt() {
myDoc = app.activeDocument;
if (radio1.value == true) {
TestVars();
}
}
function TestVars() {
#targetengine "session1";
var myDoc = app.activeDocument
var TimeMs = Number(SliderControlText.text); //Converting Text to Number
//Show Results Found as User Wish
if (DontShowResults.value == true) { //no Show only Apply
alert("you Select not to Show Results!");
}else{ //Direct Show and Apply
if (ShowResultsDirect.value == true) {
alert("you Select to Show Results in real time!");
}else{ //Show and Apply By WaitinhTime!
if (ShowResults.value == true) { //Show and Apply
alert("you Select to Show Results with Specific time!");
$.sleep(TimeMs); //Wait ms
}
}
}
alert("Do you need somthing else?, try again", "Finish Report");
}
var DontShowResults;
var ShowResultsDirect;
var ShowResults;
var SliderControlText;
var slider;
//--------------------------------------------Building the Find Options Palette-----------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------//
function CalltheFindOptions() {
#targetengine "session1";
//Find Options Window
findoptions.text = "Find Options";
//Parent - Input Panel Prepare
SelectPanel = findoptions.add("panel", undefined, undefined, { name: "panel1" });
SelectPanel.text = " Find Options : ";
SelectPanel.preferredSize.width = 1000;
SelectPanel.orientation = "row";
SelectPanel.alignChildren = ["center", "center"];
SelectPanel.spacing = 10;
SelectPanel.margins = 16;
//Children - input Panel Inside Prepare
mySelectPanelInside = SelectPanel.add("group", undefined, { name: "mySelOpt" });
DontShowResults = mySelectPanelInside.add("checkbox", undefined, "Don't Show Results");
DontShowResults.value = true; //by Default
DontShowResults.alignment = "left";
ShowResultsDirect = mySelectPanelInside.add("checkbox", undefined, "Show Results");
ShowResultsDirect.value = false; //by Default
ShowResults = mySelectPanelInside.add("checkbox", undefined, "Show Results Delayed in milliseconds(Ms) :");
ShowResults.value = false; //by Default
//Adding Slider to Control MS Time
SliderControlText = mySelectPanelInside.add ("edittext", undefined, 10, {readonly: false}); //read only prevent user Entering Nums
SliderControlText.characters = 3;
slider = mySelectPanelInside.add ("slider {minvalue: 1, maxvalue: 100, value: 10}");
//Slider Listener Plus SliderControl Text Listener
slider.onChanging = function () {SliderControlText.text = slider.value;} //Listen to Slider
var c = findoptions.show();
}
If I understand you correctly you need to use as global variables values rather than the objects. And you can change the values of global variables by onClick events.
Here is the bottom part of your code (the rest part of the code wasn't changed):
...
function TestVars() {
#targetengine "session1";
var myDoc = app.activeDocument
var TimeMs = Number(SliderControlText_text); //Converting Text to Number
//Show Results Found as User Wish
if (DontShowResults_value == true) { //no Show only Apply
alert("you Select not to Show Results!");
} else { //Direct Show and Apply
if (ShowResultsDirect_value == true) {
alert("you Select to Show Results in real time!");
} else { //Show and Apply By WaitinhTime!
if (ShowResults_value == true) { //Show and Apply
alert("you Select to Show Results with Specific time!");
$.sleep(TimeMs); //Wait ms
}
}
}
alert("Do you need somthing else?, try again", "Finish Report");
}
// values! not objects
var DontShowResults_value = true;
var ShowResultsDirect_value = false;
var ShowResults_value = false;
var SliderControlText_text = '10';
var slider_value = 10;
//--------------------------------------------Building the Find Options Palette-----------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------//
function CalltheFindOptions() {
#targetengine "session1";
//Find Options Window
findoptions.text = "Find Options";
//Parent - Input Panel Prepare
SelectPanel = findoptions.add("panel", undefined, undefined, {
name: "panel1"
});
SelectPanel.text = " Find Options : ";
SelectPanel.preferredSize.width = 1000;
SelectPanel.orientation = "row";
SelectPanel.alignChildren = ["center", "center"];
SelectPanel.spacing = 10;
SelectPanel.margins = 16;
//Children - input Panel Inside Prepare
var mySelectPanelInside = SelectPanel.add("group", undefined, {
name: "mySelOpt"
});
var DontShowResults = mySelectPanelInside.add("checkbox", undefined, "Don't Show Results");
DontShowResults.value = DontShowResults_value; //by Default
DontShowResults.alignment = "left";
// change the global variable by click
DontShowResults.onClick = function() { DontShowResults_value = DontShowResults.value }
var ShowResultsDirect = mySelectPanelInside.add("checkbox", undefined, "Show Results");
ShowResultsDirect.value = false; //by Default
// change the global variable by click
ShowResultsDirect.onClick = function() { ShowResultsDirect_value = ShowResultsDirect.value }
var ShowResults = mySelectPanelInside.add("checkbox", undefined, "Show Results Delayed in milliseconds(Ms) :");
ShowResults.value = ShowResults_value; //by Default
// change the global variable by click
ShowResults.onClick = function() { ShowResults_value = ShowResults.value }
//Adding Slider to Control MS Time
// SliderControlText = mySelectPanelInside.add("edittext", undefined, 10, {
var SliderControlText = mySelectPanelInside.add("edittext", undefined, SliderControlText_text, {
readonly: false
}); //read only prevent user Entering Nums
SliderControlText.characters = 3;
var slider = mySelectPanelInside.add("slider {minvalue: 1, maxvalue: 100, value: 10}");
// change slider every time as numbers is changes
SliderControlText.onChanging = function() {slider.value = SliderControlText.text};
//Slider Listener Plus SliderControl Text Listener
slider.onChanging = function () {
SliderControlText.text = slider.value;
// change the global variable by onChange
SliderControlText_text = SliderControlText.text;
} //Listen to Slider
findoptions.show();
}
It seems it works as intended.
As far as I can tell (I can be wrong), the cause of the problem was that the objects ShowResultsDirect, ShowResultsDirect, etc, disappears as soon as you close the palette. Because they are elements of the palette. They can't keep values if the palette is closed. That why they worked well only when you open the palette first time.

Pausing a game with ActionScript 2

I'm making a game where the player must avoid random falling objects. I dont know how to implement pausing. I've been stuck on this for 2 days!
I tried using gotoAndPlay and such, but the objects continue to run in the background. When I resume the game, they're still falling and it seems like the frame resets and loads new random falling objects.
var steps:Number = 10;
var spriteX:Number = 280;
var spriteY:Number = 650;
var alienCounter=1;
var asteroidCounter=1;
var live:Number=3;
var depthLevel=3000;
var score:Number = 0;
var gamePaused;
dropTimer=setInterval(createAlien,2000);
drpTimer2=setInterval(createAsteroid,1000);
//---- functions ----
function checkKeys()
{
if (Key.isDown(Key.RIGHT))
{
spriteX += steps;
}
else if (Key.isDown(Key.LEFT))
{
spriteX -= steps;
}
}
function updateSpaceship()
{
ship._x = spriteX;
ship._y = spriteY;
}
function createAlien()
{
var curr_alien;
curr_alien=attachMovie("alien","alien"+alienCounter,depthLevel);
curr_alien._y=40;
curr_alien._x=Math.random()*510+20;
curr_alien._xscale=curr_alien._yscale=50;
curr_alien.speed=Math.random()*10+3;
alienCounter+=1;
depthLevel+=1;
curr_alien.onEnterFrame=alienMove;
}
function alienMove()
{
if(!gamePaused)
{
this._y+=this.speed;
if(this.hitTest(ship))
{
score += 1;
trace(score);
removeMovieClip(this);
}
}
}
function createAsteroid()
{
var curr_asteroid;
curr_asteroid=attachMovie("asteroid","asteroid"+asteroidCounter,depthLevel);
curr_asteroid._y=40;
curr_asteroid._x=Math.random()*510+20;
curr_asteroid._xscale=curr_asteroid._yscale=50;
curr_asteroid.speed=Math.random()*10+3;
asteroidCounter+=1;
depthLevel+=1;
curr_asteroid.onEnterFrame=asteroidMove;
}
function asteroidMove()
{
if(!gamePaused)
{
this._y+=this.speed;
if(this.hitTest(ship))
{
live -= 1;
trace(live);
removeMovieClip(this);
if(live<=0)
{
gotoAndPlay(5);
}
}
}
}
this.onEnterFrame = function()
{
checkKeys();
updateSpaceship();
if(Key.isDown(80))
{
if(!gamePaused)
{
gamePaused=true;
gotoAndPlay(4);
}
else
{
gamePaused=false;
gotoAndStop(3);
}
}
};
i decided to use a key instead because i cannot find any solutions when trying to use a button. The pause function is not working as i expected, i need to enter key 'p' several times to pause it, but i dont want the frame resets and loads more random objects when i resume it.
try this:
remove your:
this.onEnterFrame = function()
{
checkKeys();
updateSpaceship();
if(Key.getCode() == 80)
{
if(!gamePaused)
{
gamePaused=true;
gotoAndPlay(4);
trace("AAA")
}
else
{
gamePaused=false;
gotoAndStop(3);
trace("BBB")
}
}
};
Add this (pause by pressing the 'P' key on your keyboard):
var keyListener:Object = new Object();
keyListener.onKeyUp = function() {
if(Key.getCode() == 80) {
gamePaused = !gamePaused;
mainLoop();
}
};
Key.addListener(keyListener);
function mainLoop() {
if (gamePaused) {
gotoAndStop(4); // update game actions here
trace("game is paused");
return;
}
gotoAndStop(3); // update game actions here
trace("game is running");
}
Alternatively if you need to pause using a button:
my_pause_Button.onRelease = function() { // your button instance name 'my_pause_Button'
gamePaused = !gamePaused;
mainLoop();
};
Put this in your button function or keydown function:
stage.frameRate = 0.01;

Worklight multiple busyIndicators

Is it possible to have many busyIndicators depending on context?
I tried with 4, but it doesn't work (only the last busyIndicator seems to be used, and can't be hidden):
Here's the code:
var myBusyIndicator1;
var myBusyIndicator2;
var myBusyIndicator3;
var myBusyIndicator4;
wlCommonInit(){
myBusyIndicator1 = new WL.BusyIndicator('content', {text : 'Loading data 1'});
myBusyIndicator2 = new WL.BusyIndicator('content', {text : 'Loading data 2'});
myBusyIndicator3 = new WL.BusyIndicator('content', {text : 'Loading data 3'});
myBusyIndicator4 = new WL.BusyIndicator('content', {text : 'Loading data 4'});
}
$('#myPage').on('showpage', function(e, ui){
myBusyIndicator1.show(); // 'Loading data 4' is displayed in modal window
//do some stuff
myBusyIndicator1.hide(); // modal window still, and app is not responsive anymore
});
"Busy indicator is a singleton. If you create several busy indicators, show them and then hide of them - all will be hidden." - Anton (source)
You could try to wrap it in your own "singleton", for example:
var Busy = (function () {
var busyObject;
var _show = function (message, options) {
//If you're using WL v6.0,
//see: https://stackoverflow.com/q/18501456/186909
WL.ClientMessages.loading = message;
//Others version of WL may not require
//the line above or the message parameter.
busyObject = new WL.BusyIndicator('content', options);
busyObject.show();
};
var _hide = function () {
if (busyObject !== null) {
busyObject.hide();
busyObject = null;
}
//else no busy indicator to hide
};
return {
show: _show,
hide: _hide
};
}());
//Usage:
Busy.show('message1', options1);
//Later...
Busy.hide();
//Later...
Busy.show('message2', options2);
//Later...
Busy.hide();
I did not test the code above, it's just meant to give the reader ideas, not to be copy/pasted into a project.

Can you load the PopupAppender on demand?

I am trying to use log4javascript and was wondering if there is any way to load the PopupAppender on demand.
I am seeking functionality much like the in-browser tools, where there would be an icon in my application that indicates that something has been logged and when I click it, the PopupAppender opens and allows me to view the logs.
I'm thinking I could write my own very simple appender to show the icon if there are errors, but i'm not sure how I could load up the PopupAppender and show historic messages?
You'd have to have some kind of proxy appender, as you suggest, which stores logging messages and creates a PopUpAppender on demand. Something like this:
Demo: http://jsfiddle.net/hDRpT/
Code:
function OnDemandPopUpAppender() {
this.popUpAppender = new log4javascript.PopUpAppender();
this.poppedUp = false;
this.popperUpperDisplayed = false;
this.queuedLoggingEvents = [];
}
var proto = new log4javascript.Appender();
OnDemandPopUpAppender.prototype = proto;
proto.appendQueued = function() {
for (var i = 0, loggingEvent; loggingEvent = this.queuedLoggingEvents[i++]; ) {
this.popUpAppender.append(loggingEvent);
}
this.queuedLoggingEvents.length = 0;
};
proto.popUp = function() {
this.poppedUp = true;
this.appendQueued();
};
proto.append = function(loggingEvent) {
var appender = this;
this.queuedLoggingEvents.push(loggingEvent);
if (this.poppedUp) {
this.appendQueued();
} else if (!this.popperUpperDisplayed &&
loggingEvent.level.isGreaterOrEqual(log4javascript.Level.ERROR)) {
var popperUpper = document.createElement("div");
popperUpper.style.border = "solid red 2px";
popperUpper.innerHTML = "There are error messages in the log. Click to open.";
popperUpper.onclick = function() {
appender.popUp();
}
document.body.appendChild(popperUpper);
this.popperUpperDisplayed = true;
}
};
var log = log4javascript.getLogger("main");
log.addAppender(new OnDemandPopUpAppender());
log.debug("A debug message");
log.error("A horrible error!");

vline add remote stream for callee fail

I am trying to use your api in a custom app with imported users.
Everything works fine (auth_token, login, call initiation) , but when the callee should get a response and add the remotestream nothing happens. no errors get shown in the console.
I would appreciate if someone takes a look at the code and tells me what i m missing.
I tried the vline demo at https://freeofcinema.vline.com and it worked with the same browsers and conditions between the two computers. In my app it is a http , but i tried it also with https, and the same problem came up. This is some simplified code i used to test the api.
var Streams = [];
var Vsession = null;
var Vline = (function(){
var Client;
var authToken;
var service_id = 'freeofcinema';
var profile = null;
var Person;
var Calls = [];
var onMessage = function(event){
//alert('message');
var msg = event.message, sender = msg.getSender();
console.log(sender.getDisplayName() +'sais: '+ msg.getBody());
console.log(event);
}
var onMediaSession = function(event){
console.log(event);
var mediaSession = event.target;
InitSession(mediaSession);
}
function Call(mediaSession) {
mediaSession.
on('change', alert_info);
}
function alert_info(b){
console.log(b);
}
function InitSession(mediaSession){
mediaSession.on('mediaSession:addRemoteStream', function(event) {
alert('addRemoteStream');
});
mediaSession.on('mediaSession:addLocalStream', function(event) {
alert('addLocalStream');
});
mediaSession.on('mediaSession:removeLocalStream mediaSession:removeRemoteStream', function(event) {
console.log('removedStream');
});
Calls.push(new Call(mediaSession));
}
return {
init : function(){
if(profile){
return;
}
profile = {
"displayName" : //some getusrname function...
};
$.post('vtoken.php',{//get auth token
id : Comm.Voip_user().id
},function(data){
authToken = data;
Client = vline.Client.create({
"serviceId": service_id,
"ui" : true
});
Client.on('recv:im', onMessage , this);
Client.on('add:mediaSession', onMediaSession, this);
Client.on('login', function(e) {
Vsession = e.target;
//alert('loged in');
});
Client.login(service_id, profile, authToken);
});
},
getPerson : function(id){//id of user to call
if(Vsession){
Vsession.getPerson(id).
done(function(person){
Person = person;
Vsession.startMedia(id);
});
}
}
}
}());
Thank you for your response.
I tried with one user from the app, and another from the https://freeofcinema.vline.com, and the same problem occured. Also the call (in pending state) gets terminated after a short while..
When passing ui:true when creating the client, you do not have to handle the media sessions yourself. Just comment the line Client.on('add:mediaSession', onMediaSession, this); and it should just work.