Ionic Schedule a Popover page to display every N days - javascript

I am looking to display a page every N days or for example every 3/4 days which will just popover the screen
So far from digging about I see ionics local notifications offers a really nice way to schedule standard notifications within an app but it does not allow you to change the notification data to use a page.
Is there a way to do this kind of thing natively within ionic ?

Does it need to be a popover? Couldn't you just keep a record of the last time the page was show to the user using localStorage or Storage and when the app is launched check if it's time to show the page again and then redirect to that page. If you do want it to be a popover it's pretty simple. You create the page like normal then add it as the component in your poperover constructor. Something like this in your platform.ready():
const daysSinceLastShown = parseint(localStorage.get('daysSinceLastShown'), 10);
if (daysSinceLastShown < 4) {
daysSinceLastShown++;
localStorage.put('daysSinceLastShown', daysSinceLastShown);
} else {
localStorage.put('daysSinceLastShown', 0);
presentPopover();
}
async presentPopover() {
const popover = await this.popoverCtrl.create({
component: MyPopoverPage,
});
return await popover.present();
}

Related

How to execute a function only once in a day(&only if the app is opened)?

Let i have a function
function alert(){
alert("notification")
}
this function is a part of a mobile app, i want to show this alert(execute function) only once in a day only if user opens the app,
if user didn't open the app for so many days it shouldn't execute that function for that much days.
How to implement in javascript?
can anyone provide a common logic that can be used every where even in ios or ionic...etc ?
Select somewhere that you can store persistent data. That will depend on whatever APIs the app supplies.
Use new Date() to find out the current time.
Compare that to the stored time the function last executed fully. If it is less than a day, return immediately.
Otherwise, store the new time and let the rest of the function run.

Keeping user logged in, in a react flux app?

I am working on a react-flux app where I am using sessionStorage to keep a user logged in by checking if email and auth token are available in sessionStorage. If they are available and time since login is less than 15 minutes, I trigger off a flux action to log the user in. I also have another function that irrespective logs the user out after 15 minutes by clearing out the sessionStorage.
It works fine, until I refresh the page. At this point, the setInterval function that logs the user out after 15 minutes, resets itself.
Here's the code to make sense of what I am referring to:
In my parent component I have the following functions that I call inside componentDidMount function.
checkSession: function() {
if (!_.isNull(window.localStorage)) {
var currentTimeStamp = Date.parse(new Date());
var logInStamp = window.sessionStorage.time;
var difference = currentTimeStamp - logInStamp;
if (Math.floor((difference / 1000) / 60) < 15) {
var data = {
email: window.sessionStorage.email,
scheduler_slug: window.sessionStorage.slug
};
ActionCreator.loginUser(data);
}
}
},
logOut: function() {
if (this.state.isLoggedIn === true) {
window.sessionStorage.clear();
ActionCreator.logOutUser();
}
},
componentDidMount: function() {
Store.addChangeListener(this._onChange);
this.checkSession();
setInterval(this.logOut, 900000);
}
I am setting the key values for sessionStorage on success of my ajax call for creating a session. In subsequent api calls, i send back the token i received in response from the first call in my response header for authentication.
My question is 2 fold:
1) Is my current approach enough to maintain user session? Would using cookies be better?
2) If my current approach is fine, then I need to figure out a way to prevent timer from resetting on page refresh which I thought would be an easy fix but everything I am seeing involves using cookies. Is there another way?
This is very subjective. If this approach works for you, that is ok. Cookies are also a good option for this, it just depends. You mention that you have some troubles using your current approach (mostly on page refresh). A cookie could help, but isn't some silver bullet either. Choose wisely what fits your app the best (think about if you ever want your server calls to be called from libraries etc, which might introduce more annoyances when using cookies.
Since you already store something in the sessionStorage, you can also choose to store the data simply in localStorage. This will ensure it stays the same, and since the time is saved as well you're basically providing your own session storage, that survives a refresh.
A side note, sessionStorage shouldn't reset itself on a refresh, it lives in a tab-context. So if you open a new tab you do get a new session, if you refresh you should be having the same storage. Depending on your app you might want to take a look if you somewhere replace the data, or if the refresh happens in a different tab.

Ionic Angular - Resetting scope variables

I have a flow of few pages/views starting from first page to last page. This is pretty much based on the Ionic tutorial.
I update a factory "Info" with some data as I proceed with the flow. In the final page, after displaying the "summary info" to the user, I use $state.go('firstPage') to navigate back to the first page.
When I make a different selection in the first page this time, it doesn't seem to take effect in the view.
I tried the suggestion from here but that didn't help me. I tried resetting the variables again, but that doesn't help either.
angular.module('my.services', [])
.factory("Info", function(){
// All user data
var infoData = {
type: "",
level: 0
};
var originalInfoData = angular.copy(infoData);
// Reset data
infoData.resetUserDetails = function() {
userData = angular.copy(originalInfoData);
};
Final Page Controller
$scope.finish = function() {
UseInfo.resetUserDetails();
$state.go('firstPage');
}
This takes me back to first page but even though I select something different this time, the pages seem to remember what I did in my first run.
The question is - how do I clear things up so the user can do something else after getting back to the first page without remembering previous selections.

How to code Websockets/AJAX for frequent database updates? Or is there a better method?

I’m making a html & Javascript game and I’m currently trying to write some code that will show the player’s gold balance on the screen and make it decrement by 1 every time the player clicks on a Javascript object (this object is placed in a div on the html page).
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a <div> but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
I don’t want the figure to decrement below 0. Instead, whenever it reaches 0 I want to initiate a Javascript modal to inform the player that they’ve run out of coins.
~~
Originally I was trying to use websockets to display the player’s balance on screen, but I found it very confusing (I’m a beginner at programming in general), so I’m now trying to load the balance on page load, then post the updated balance amount back to my database using AJAX every 60 seconds, or whenever the user closes the browser window, refreshes the page or navigates away from the page. I don’t know if it’s possible to do all these things, or where to start, maybe this is a really bad way to go about this and maybe it's not scalable (maybe the database wouldn't support constant updates from 1000s of players by using this method)?
I would really appreciate any advice or help anyone could give me on any of this.
Thanks in advance!
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
Here are two divs: you store the total number of coins in one and you click the second one to lose coins
<div id="coins">10</div>
<div onCLick="javascript:loseCoin()">If you click here it will cost you 1 coin</div>
Using a function to decrement the cost.
function loseCoin(){
var coins = getElementByid("coins");
var coins_nr = parseInt(coins.innerHTML,10);
if( coins_nr> 0 ){
coins.innerHTML = coins_nr - 1;
} else {
showModal();
}
}
Where showModal() will be your modal (ask if you don't know how to make it)
As for updating the database every 60 sec, you would need a timer loop such as:
setInterval(function () {
// get number of coins from your div's innerHTML
// then call your ajax controller to update DB
}, 60000);
An example of ajax using javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("POST", "url_of_your_controller_here", true);
xhr.send("coins="+ coins_nr);
(maybe the database wouldn't support constant updates from 1000s of
players by using this method)?
Any decent server should have no problem handling 1000 requests every 60 sec, but it may depend on how many other requests it has and the complexity of your requests.
If you are just trying to decrement a visible counter in the window on each click, you can do something like this:
HTML:
<div id="coinsRemaining">20</div>
code:
// use whatever click handler is appropriate to your app
document.addEventListener("click", function(e) {
var elem = document.getElementById("coinsRemaining");
// get current display text and convert to number
var cnt = +elem.textContent;
--cnt;
if (cnt >= 0) {
elem.textContent = cnt;
}
if (cnt <= 0) {
alert("There are no more coins");
}
});
Working demo: http://jsfiddle.net/jfriend00/s9jb6uhf/
It seems like you don't need to update the database on every click unless there's some realtime aspect of your coin balance that affects other users. If you're just keeping track of your coin balance for future web page visits, then you could update the database much less often than every click.

ExtJs 4.2 ref-selector vs Ext.getcmp() vs Ext.ComponentQuery.query()

I was asked to develop a tab panel with 6 tabs, each having 30 to 40 elements. Each tab is acting as a form in accumulating the details of a person and the last tab is a Summary page which displays all the values entered in the first five tabs. I was asked to provide summary as a tab because, the user can navigate to summary tab at any instance and look at the details entered by him/ or glace the summary. i am following ExtJs MVC pattern. Payload is coming from / going to Spring MVC Application. (JSON)
Using tab change event in controller and if the newtab is summary I am rendering the page with show hide functionality.
Method 1 :In controller I have used Ext.getCmp('id of each element inside the tabs') and show hide the components in summary tab based on the value entered by the user. This killed my app in IE8 popping a message saying that the "script is slow and blah blah..." i had to click on NO for 5 to 6 times for the summary tab to render and display the page.
Method 2 :In controller I used ref and selectos to acccess all the items in tabs. I have used itemId for each and every field in summary tab. like this.getXyz().show(). I thought it would be fast. Yes it was in Google chrome. but my app in IE8 is slow compared to goolge chrome/firefox
Any suggestions regarding this and plan to decrease page render time. The summary page has more than 1000 fields. Please feel free to shed ur thoughts or throw some ideas on this.
thank you!!
I've got a few suggestions you can try. First, to answer your title, I think the fastest simple way to lookup components in javascript is to build a hash map. Something like this:
var map = {};
Ext.each(targetComponents, function(item) {
map[item.itemId] = item;
});
// Fastest way to retrieve a component
var myField = map[componentId];
For the rendering time, be sure that the layout/DOM is not updated each time you call hide or show on a child component. Use suspendLayouts to do that:
summaryTabCt.suspendLayouts();
// intensive hide-and-seek business
// just one layout calculation and subsequent DOM manipulation
summaryTabCt.resumeLayouts(true);
Finally, if despite your best efforts you can't cut on the processing time, do damage control. That is, avoid freezing the UI the whole time, and having the browser telling the user your app is dead.
You can use setTimeout to limit the time your script will be holding the execution thread at once. The interval will let the browser some time to process UI events, and prevent it from thinking your script is lost into an infinite loop.
Here's an example:
var itemsToProcess = [...],
// The smaller the chunks, the more the UI will be responsive,
// but the whole processing will take longer...
chunkSize = 50,
i = 0,
slice;
function next() {
slice = itemsToProcess.slice(i, i+chunkSize);
i += chunkSize;
if (slice.length) {
Ext.each(slice, function(item) {
// costly business with item
});
// defer processing to give time
setTimeout(next, 50);
} else {
// post-processing
}
}
// pre-processing (eg. disabling the form submit button)
next(); // start the loop
up().down().action....did the magic. I have replaced each and every usage of Ext.getCmp('id'). Booooha... it's fast and NO issues.
this.up('tabpanel').down('tabName #itemIdOfField').actions.
actions= hide(), show(), setValues().
Try to check deferredRender is true. This should only render the active tab.
You also can try a different hideMode. Especially hideMode:'offsets ' sounds promising
Quote from the sencha API:
hideMode: 'offsets' is often the solution to layout issues in IE specifically when hiding/showing things
As I wrote in the comment, go through this performance guide: http://docs.sencha.com/extjs/4.2.2/#!/guide/performance
In your case, this will be very interesting for you:
{
Ext.suspendLayouts();
// batch of updates
// show() / hide() elements
Ext.resumeLayouts(true);
}

Categories