Titanium Back Button - Always closes my App - javascript

I have a new problem with my App, i'm using Appcelerator Titanium for development.
I want to lock the Backbutton from my Device, so the App wont close everytime when i use him. I want to close the App only if i'm at the primarymenu. So this is my code:
Ti.UI.currentWindow.addEventListener('android:back',function(){
alert(Ti.App.PositionNow);
if(Ti.App.PositionNow=='0') {
alert('do quit');
} else if(Ti.App.PositionNow=='1') {
Ti.App.multi_tableView.addEventListener('click',myfunction);
var duration = 300;
var setOldOpacity = Titanium.UI.createAnimation();
setOldOpacity.opacity = 1;
setOldOpacity.zIndex = 1;
setOldOpacity.duration = duration;
var setOldBottom = Titanium.UI.createAnimation();
setOldBottom.bottom = 0;
setOldBottom.duration = duration;
var setOldTop = Titanium.UI.createAnimation();
setOldTop.top = 0;
setOldTop.duration = duration;
var animationHandler2 = function() {
setOldTop.removeEventListener('complete',animationHandler2);
Ti.App.multi_view_first.animate(setOldTop);
Ti.App.multi_view_second.animate(setOldBottom);
Ti.App.multi_tableView.animate(setOldOpacity);
};
setOldTop.addEventListener('complete',animationHandler2);
Ti.App.multi_view_first.animate(setOldTop);
Ti.App.multi_view_second.animate(setOldBottom);
Ti.App.multi_tableView.animate(setOldOpacity);
alert('hallo1');
Ti.App.PositionNow = 0;
}
return false;
});
I have an variable where i track the position from the user at the hierachy from the menu. So the App should only close when the position is "0".
If the position is "1", there should be an animation, so this works, but during the animation, the app closes instantly.
The code of the window is this:
Ti.App.hs_win = Ti.UI.createWindow({
url: '/sites/homescreen/index.js',
navBarHidden: true,
fullscreen: true,
modal:true,
theme: "Theme.Titanium",
orientationModes: [Ti.UI.PORTRAIT]
});

The event you're monitoring android:back is deprecated. Please use androidback event.
The second step is to stop the event bubbling further in the event handler chain. For this you need to cancel the event:
Ti.UI.currentWindow.addEventListener('androidback',function(event){
event.cancelBubble = true;
}
Also you have to modify your window and set exitOnClose property to false

Related

How do I change the name of the button and save it when reloading the page with javascript

I have a page with a button that when I click on it it changes but if I reload the page it returns as it is without changing
html
<button onload="form1.reset();" class="button" id="movetool10" onclick="movetool10();stoptool10()">حجز</button>
javascript
var clickCounter10 = 0;
var movetool10 = document.getElementById('movetool10')
movetool10.onclick = function() {
clickCounter10++;
if (clickCounter10 ===2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'click !';
}
else {
document.getElementById('movetool10').innerHTML = 'click me';
}
};
You can make use of localStorage, save the last counter value there and fetch it in the begining, if it exists, use it. Otherwise, initialize the counter with 0 for first time render (or someone clears the localStorage). Please note that this is only on client side, so if the user clears the localStorage, the counter will be reinitialised.
Right now, the button shows up from its last state. It is toggling between the two states, you can change the logic however you want, but this is how you can make use of localStorage.
JSFiddle
var clickCounter10 = window.localStorage.getItem('clickCounter10') || 0;
var movetool10 = document.getElementById('movetool10');
changeBtn();
movetool10.onclick = function() {
clickCounter10++;
window.localStorage.setItem('clickCounter10', clickCounter10);
changeBtn();
};
function changeBtn() {
clickCounter10 = parseInt(clickCounter10, 10);
if (clickCounter10 === 2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'click !';
} else if(clickCounter10 !== 0) {
document.getElementById('movetool10').innerHTML = 'click me';
}
}

How to remove mousemove from events that stop idlemonitor?

I want to use a simple p:idleMonitor for some logic.
But in my case, i don't want to restart the idlemonitors counter for a mousemove (only for click etc.)
Is this possible with javascript or with something else? The idlemonitor does not have any attribute for that configuration.
Add this code to a JS file that loads after PrimeFaces to MonkeyPatch your IdleMonitor to only stop on keydown and click events.
The key is this line events: "keydown click" // define active events
This is based on PrimeFaces 8.
if (PrimeFaces.widget.IdleMonitor) {
PrimeFaces.widget.IdleMonitor.prototype.init = function(cfg) {
PrimeFaces.widget.BaseWidget.prototype.init.call(this, cfg);
var $this = this;
$(document).on("idle.idleTimer" + this.cfg.id, function() {
if ($this.cfg.onidle) {
$this.cfg.onidle.call($this);
}
$this.callBehavior('idle');
})
.on("active.idleTimer" + this.cfg.id, function() {
if ($this.cfg.onactive) {
$this.cfg.onactive.call($this);
}
$this.callBehavior('active');
});
var opts = {
idle: false, // indicates if the user is idle
timeout: this.cfg.timeout, // the amount of time (ms) before the user is considered idle
events: "keydown click" // define active events
};
$.idleTimer(opts, document, this.cfg.id);
if (cfg.multiWindowSupport) {
var globalLastActiveKey = $this.cfg.contextPath + '_idleMonitor_lastActive' + this.cfg.id;
// always reset with current time on init
localStorage.setItem(globalLastActiveKey, $(document).data('idleTimerObj' + this.cfg.id).lastActive);
$this.timer = setInterval(function() {
var idleTimerObj = $(document).data('idleTimerObj' + $this.cfg.id);
var globalLastActive = parseInt(localStorage.getItem(globalLastActiveKey));
var localLastActive = idleTimerObj.lastActive;
// reset local state
if (globalLastActive > localLastActive) {
// pause timer
$.idleTimer('pause', document, $this.cfg.id);
// overwrite real state
idleTimerObj.idle = false;
idleTimerObj.olddate = globalLastActive;
idleTimerObj.lastActive = globalLastActive;
idleTimerObj.remaining = $this.cfg.timeout;
// resume timer
$.idleTimer('resume', document, $this.cfg.id);
}
// update global state
else if (localLastActive > globalLastActive) {
localStorage.setItem(globalLastActiveKey, localLastActive);
}
}, 2000);
}
}
};

Scroll Function Firing Multiple Times Instead of Once

I am trying to create a website that automatically scrolls to each section upon a single scroll action. This means that the code has to check if the page is scrolled up or scrolled down. I believe the code below solves my problem but the scroll action is fired more than once while the page is scrolling. You will see that the first alert in the if statement reaches 5 instead of the desired 1. Any help on the matter would be highly appreciated.
[Note] I am using the velocity.js library to scroll to each section within the container.
var page = $("#content-container");
var home = $("#home-layer-bottom");
var musicians = $("#musicians");
var athletes = $("#athletes");
var politics = $("#politics");
var bio = $("#politics");
var pages = [ home,musicians,athletes,politics,bio ];
var pageCur = 0;
var lastScrollTop = 0;
page.scroll(function(){
var st = $(this).scrollTop();
var pageNex = pageCur + 1;
if (st > lastScrollTop){
alert(pageNex);
pages[pageNex].velocity("scroll", { container: $("#content-container") });
} else {
alert(pageCur-1);
pages[pageCur-1].velocity("scroll", { container: $("#content-container") });
}
lastScrollTop = st;
pageCur = pageNex;
});
The scroll event (as well as the resize event) fire multiple times as a user does this. To help this, the best practice is to debounce. However, I've never gotten that to work. Instead, I use a global boolean to check if the function has fired.
var scrolled = false;
page.on('scroll', function(){
if(!scrolled){
scrolled = true;
//do stuff that should take a while...
scrolled = false;
};
});
This worked for me!
var ScrollDebounce = true;
$('.class').on('scroll',
function () {
if (ScrollDebounce) {
ScrollDebounce = false;
//do stuff
setTimeout(function () { ScrollDebounce = true; }, 500);
}
})

Android + jQuery - second on swipeleft wont execute

I have to do some Special things for my Webpage to work on Android the correct way. Some Images are displayed (one visible, the other unvisible) and through swipe it should be possible to Change them. No Problem so far on all OS.
But it also should be possible to zoom. Now Android starts to be Buggy. It stops the zoom-gesture because of the swipe callback. The callback itself doesn't Change the page because the view is zoomed, so there should be no break.
Now I work arround through turning my swipeleft and swiperight off while two fingers touching the Display, and tourning back on if the fingers leave the Display.
On First run I can swipe, then I can zoom with no break, but then I can't swipe anymore. The function to set the callbacks back on again is called, it set's the callbacks, but they won't be executed...
Here's the code:
app.utils.scroll = (function(){
var $viewport = undefined;
var swipeDisabled = false;
var init = function(){
$viewport = $('#viewport');
$viewport.mousewheel(mayChangePage);
// On touchstart with two fingers, remove the swipe listeners.
$viewport.on('touchstart', function (e) {
if (e.originalEvent.touches.length > 1) {
removeSwipe();
swipeDisabled = true;
}
});
// On touchend, re-define the swipe listeners, if they where removed through two-finger-gesture.
$viewport.on('touchend', function (e) {
if (swipeDisabled === true) {
swipeDisabled = false;
initSwipe();
}
});
initSwipe();
}
var mayChangePage = function(e){
// If page is not zoomed, change page (next or prev).
if (app.utils.zoom.isZoomed() === false) {
if (e.deltaY > 0) {
app.utils.pagination.prev(e);
} else {
app.utils.pagination.next(e);
}
}
// Stop scrolling page through mouse wheel.
e.preventDefault();
e.stopPropagation();
};
var next = function (e) {
// If page is not zoomed, switch to next page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.next(e);
}
};
var prev = function (e) {
// If page is not zoomed, switch to prev page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.prev(e);
}
};
var initSwipe = function () {
// Listen to swipeleft / swiperight-Event to change page.
$viewport.on('swipeleft.next', next);
$viewport.on('swiperight.prev', prev);
};
var removeSwipe = function () {
// Remove listen to swipeleft / swiperight-Event for changing page to prevent android-bug.
$viewport.off('swipeleft.next');
$viewport.off('swiperight.prev');
};
$(document).ready(init);
}());
Pastebin
Any ideas what I can do to get the Events back on again?
Thanks for all Ideas.
Regards
lippoliv
Fixed it:
jQuery Mobile itself prevents the swipe Event if an handler is registered, to kill an "scroll".
So I overwrote the $.event.special.swipe.scrollSupressionThreshold value and set it to 10000, to prevent jQueryMobile's preventDefault-call:
$.event.special.swipe.scrollSupressionThreshold = 10000;
Now my Code Looks like
app.utils.scroll = (function(){
var $viewport = undefined;
var swipeDisabled = false;
var init = function(){
$viewport = $('#viewport');
$viewport.mousewheel(mayChangePage);
// See #23.
$.event.special.swipe.scrollSupressionThreshold = 10000;
// Listen to swipeleft / swiperight-Event to change page.
$viewport.on('swipeleft.next', next);
$viewport.on('swiperight.prev', prev);
}
var mayChangePage = function(e){
// If page is not zoomed, change page (next or prev).
if (app.utils.zoom.isZoomed() === false) {
if (e.deltaY > 0) {
app.utils.pagination.prev(e);
} else {
app.utils.pagination.next(e);
}
}
// Stop scrolling page through mouse wheel.
e.preventDefault();
e.stopPropagation();
};
var next = function (e) {
// If page is not zoomed, switch to next page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.next(e);
}
};
var prev = function (e) {
// If page is not zoomed, switch to prev page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.prev(e);
}
};
$(document).ready(init);
}());
Thanks to Omar- who wrote with me several minutes / hours in the jquery IRC and gave some suggestions regarding overwriting Standard values for jQueryMobile.

What is the better way to get mouse hold time?

I'm trying to count the time that player is holding the mouse button down. I tried this but it didn't works:
var Game = cc.Layer.extend({
count: false,
countTimer: null,
init: function () {
var selfPointer = this;
this.canvas.addEventListener('mousedown', function(evt) {
selfPointer.count = true;
selfPointer.countTimer = window.setTimeout(selfPointer.Count(), 1);
});
this.canvas.addEventListener('mouseup', function(evt) {
selfPointer.count= false;
window.clearTimeout(selfPointer.countTimer);
});
},
Count: function() {
if (this.count)
{
window.setTimeout(this.Count(), 1);
}
}
This is a part of my code(for brevity) that I want to do an action any 1 milisecond if player is holding the button.
This isn't working besides, I presume that is a better way to do this than mine way. Any ideas?
Why do you use timeouts for this simple task? You can just get time of mousedown, time of mouseup and calculate difference of them. Anyway, timer resolution in browsers is less than 1ms. Read this article of Nickolas Zakas to get more info about time resolution.
Code is:
var Game = cc.Layer.extend({
init: function () {
var holdStart = null,
holdTime = null;
this.canvas.addEventListener('mousedown', function(evt) {
holdStart = Date.now()
});
this.canvas.addEventListener('mouseup', function(evt) {
holdTime = Date.now() - holdStart;
// now in holdTime you have time in milliseconds
});
}
Well if you are targeting newer browsers that are HTML5 compatible you can use web workers for this kind of task. Simply post a message to the web worker on mouse press to start the timer. The web worker can post a message back every 1 ms ish to trigger your in game action and then on mouse release, post another message to the web worker telling it to stop.
Here is just a quick example of how that would work. You would need to run from a local server to have web workers working.
Game.js
function start() {
var worker = new Worker("ActionTrigger.js");
worker.addEventListener('message', function(objEvent) {
console.log("Holding");
});
worker.postMessage("start");
window.onmousedown = function() {
console.log("Mouse press");
worker.postMessage("startTrigger");
}
window.onmouseup = function() {
console.log("Mouse release");
worker.postMessage("endTrigger");
}
}
ActionTrigger.js
var trigger = false;
var interval = 1;
self.addEventListener('message', function(objEvent) {
if(objEvent.data == 'startTrigger')
trigger = true;
else if(objEvent.data == 'endTrigger')
trigger = false;
else if(objEvent.data == 'start')
timerCountdown();
});
function timerCountdown() {
if(trigger)
postMessage("");
setTimeout(timerCountdown,interval);
}
You could use something like this:
http://jsfiddle.net/yE8sh/
//Register interval handle
var timer;
$(document).mousedown(function(){
//Starts interval. Run once every 1 millisecond
timer=self.setInterval(add,1);
});
$(document).mouseup(function(){
//Clears interval on mouseup
timer=window.clearInterval(timer);
});
function add(){
//The function to run
$("body").append("a");
}

Categories