Receive Events in a javascript and print it in a separate window? - javascript

I have a pushlet in my project which receives the push events (i.e.,) if a user click on some buttons it will get the action and sends the message to the main jsp page through a javascript. Now, i have received datas through the pushlet and retrieved those in a javascript.
function setUserDataEvent(UserDataEvent) {
try {
alert(UserDataEvent);
}
catch(er) {
}
}
Where userDataEvent is the event which i received through pushlet. I am getting continuous alerts like for eg.,(a=b) and then (c=d). I have to receive get those values and then print those in a separate window in javascript using window.open()....
Any suggestions???????

I think you have to go over a cookie.
Save the event data in a cookie, then open the window and then, in your script in the window, read the data and delete the cookie.

I arrived at a solution and its working fine!!!!!
var testWindow;
var testData="";
function setUserDataEvent(UserDataEvent) {
try {
if(!testData) {
testData = UserDataEvent;
} else {
testData += UserDataEvent;
}
if(!testWindow) {
var x = 235;
var y = 370;
testWindow = window.open('','q',"location=no,directories=no,status=no,menubar=no,scrollbars=no,resize=no,width=" + x + ",height=" + y);
}
testWindow.document.write(testData);
testWindow.document.close();
testWindow.focus();
}
catch (er)
{
}
}

Related

testing 2-player socket.io game. updating a label is affecting both pages

I don't understand why updating a label on one page is affecting the label on another page. I did not think the DOM was shared like that. Opening one tab or page successfully updates the label to 'player1', but when I open another tab/pg, it updates both labels to 'player2'.
<script>
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.emit('join');
socket.on('joinSuccess', function (playerSlot) {
if (playerSlot === 'player1') {
$("#playerID").text("you are player1");
} else if (playerSlot === 'player2') {
$("#playerID").text("you are player2");
}
}); //end joinSuccess
}); //end connect
I am merely trying to notify the user which player they are.
solution:
else if (playerSlot === 'player2') {
var elm = $("#playerID");
var empty = !elm.text().trim();
if (empty) {
elm.text("you are " + playerSlot);
}
}
Are you pushing the 'joinSuccess' message when new user joins? In such case this message will be passed to both the pages with same playerSlot value. So, all pages will be updated last joined player name.
In such case you can handle this with simple condition,
socket.on('joinSuccess', function (playerSlot) {
var elm = $("#playerID");
if (!elm.text().trim()) {
elm.text("you are " + playerSlot);
}
});

how to show image on page refresh in localstorage

what i need
i need to show image when user select particular event. consider add to favorite functionality.
when user click on image data is store in array.
then user click particular image ,after reloading page another image should be shown at that position.
js code
on dom ready
show image on particular clicked div.
$(document).ready(function() {
console.log(localStorage);
if (localStorage.id!='')
{
var image_url='/images/star1_phonehover.png';
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
});
js code to set and get items
function favaorite(sess_id,name,city,country,event_url,pointer)
{
/* clear storage code*/
//window.localStorage.clear();
/* store imageurl in localstorage */
var imageUrl='/images/star1_phonehover.png';
// Save data to the current local store//
if (typeof(localStorage) == 'undefined' ) {
console.log('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else
{
try {
// Put the object into storage
localStorage.setItem('id' ,JSON.stringify(sess_id));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!');//data wasn't successfully saved due to quota exceed so throw an error
}
}
try {
// Put the object into storage
localStorage.setItem('name' ,JSON.stringify(name));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!');//data wasn't successfully saved due to quota exceed so throw an error
}
}
try {
// Put the object into storage
localStorage.setItem('city',JSON.stringify(city));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('country',JSON.stringify(country));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('event_url',JSON.stringify(event_url));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('imageUrl',JSON.stringify(imageUrl));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
/* fetch the data using from localstorage */
var id= [];
var name= [];
var city = [];
var country =[];
var event_url= [];
// Retrieve the object from storage
//var id, city, country,event_url;
var id = localStorage.getItem('id');
id = JSON.parse(id);
console.log(id);
var name = localStorage.getItem('name');
name = JSON.parse(name);
console.log(name);
var name = localStorage.getItem('name');
name = JSON.parse(name);
var city = localStorage.getItem('city');
city = JSON.parse(city);
console.log(city);
var country = localStorage.getItem('country');
country = JSON.parse(country);
console.log(country);
var event_url = localStorage.getItem('event_url');
event_url = JSON.parse(event_url);
///console.log(event_url);
var image_url = localStorage.getItem('imageUrl');
//event_url = JSON.parse(event_url);
alert(image_url);
//console.log(image_url);
//console.log($(pointer).closest('.evt_date').find('.star'));
if (id!='' )
{
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
}
Problem
i have stored image in localstorage and trying load image on page refresh so ist applying on all div which div i have not clciked marke as favorite.
here is snapshot of json data:
in snapshot you could see localstorage only stores single json.
i need to ask is localstorage don"t store whole data that i have clicked its hows recent data in localstorage.
output should be
select particular data and store in localstorage in nested json string.
and on dom load or page refresh show particular on div whose id stored in localstorage.
i have tried a solution
$(document).ready(function() {
console.log(localStorage.id);
if (localStorage.id==30301)
{
var image_url='/images/star1_phonehover.png';
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
});
then also it is applying image on all divs though it should apply on particular saved it of localstorage.
It sounds like you're trying to show a 'star' next to items a user has 'favorited' and you want to store these favorites in local storage.
Ignoring your existing code, I'd use a strategy like this:
1) Save the id's for each favorited item into an array and store that in local storage
localStorage.setItem('favorites' ,JSON.stringify(arrayOfFavorites));
2) On dom ready, add an attribute to all the 'favorited' items. Note, to do this you'll need to add some identifying attribute to each dom node you care about. I assume you have something like <div class='item' data-id='your-id'></div>:
var list = getArrayFromLocalStorage('favorites');
list.forEach(function(id) {
$('.item[data-id="' + id + '"').attr('favorite', '');
}
3) Finally, in your css, enable the background image for all items with the favorite attribute
item[favorite] {
background-image: '/images/star1_phonehover.png'
}
Hopefully this strategy points you in the right direction.

How to avoid using a global variable, when closing an EventSource in internal links?

I have a web application, where some internal pages use an EventSource to receive live updates from the server.
The client code looks like this:
var LiveClient = (function() {
return {
live: function(i) {
var source = new EventSource("/stream/tick");
source.addEventListener('messages.keepalive', function(e) {
console.log("Client "+ i + ' received a message.');
});
}
};
})();
You can see a live demo on heroku: http://eventsourcetest.herokuapp.com/test/test/1. If you open the developer console, you will see a message printed every time an event is received.
The problem is that when visiting internal links, the EventSource remains open, causing messages to be printed even after the visitor moves from one page to another - so if you visit the three links on the top, you will get messages from three sources.
How can I close the previous connection after the user moves from one internal page to another?
A hacky workaround that I tried was to use a global variable for the EventSource object, like this:
var LiveClient = (function() {
return {
live_global: function(i) {
// We set source as global, otherwise we were left
// with sources remaining open after visiting internal
// pages
if (typeof source != "undefined" && source != null) {
if (source.OPEN) {
source.close();
console.log("Closed source");
}
}
source = new EventSource("/stream/tick");
source.addEventListener('messages.keepalive', function(e) {
console.log("Client "+ i + ' received a message.');
});
}
};
})();
Demo here: http://eventsourcetest.herokuapp.com/test/test_global/1, but I am looking for a solution that would avoid the use of a global variable if possible.
The HTML code that is generated is:
Page 1 |
Page 2 |
Page 3 |
<p>This is page 3</p>
<script>
$(function() {
LiveClient.live_global(3);
});
</script>
or with LiveClient.live_global(1); for the case with the global variable.
Try this. I haven't tested it. If it works, you might be able to replace LiveClient.source with this.source which is a lot cleaner imo.
var LiveClient = (function() {
return {
source: null,
live_global: function(i) {
// We set source as global, otherwise we were left
// with sources remaining open after visiting internal
// pages
if (typeof LiveClient.source != "undefined" && LiveClient.source != null) {
if (source.OPEN) {
source.close();
console.log("Closed source");
}
}
LiveClient.source = new EventSource("/stream/tick");
LiveClient.source.addEventListener('messages.keepalive', function(e) {
console.log("Client "+ i + ' received a message.');
});
}
};
})();

Push notifications ti.App resume event handler (titanium)

Here is my code
function registerPushNotifications() {
Titanium.Network.registerForPushNotifications({
types : [Titanium.Network.NOTIFICATION_TYPE_BADGE, Titanium.Network.NOTIFICATION_TYPE_ALERT],
success : function(e) {
var deviceToken = e.deviceToken;
Ti.API.info("Push notification device token is: " + deviceToken);
Ti.API.info("Push notification types: " + Titanium.Network.remoteNotificationTypes);
Ti.API.info("Push notification enabled: " + Titanium.Network.remoteNotificationsEnabled);
Ti.API.error("device Token is: " + e.deviceToken);
//return device Token to store in Model.
return e.deviceToken;
},
error : function(e) {
Ti.API.info("Error during registration: " + e.error);
},
callback : function(e) {
// called when a push notification is received.
//var data = JSON.parse(e.data);
var data = e.data;
var badge = data.badge;
if (badge > 0) {
Titanium.UI.iPhone.appBadge = badge;
}
var message = data.message;
if (message != '') {
var my_alert = Ti.UI.createAlertDialog({
title : '',
message : message
});
my_alert.show();
}
Ti.App.addEventListener('resume', function() {
alert('do another event if coming from background');
}
});
};
Depending on whether the push notification comes from the background or foreground I want to run different events.
I have tried
Ti.App.addEventListener('resume', function() {
but this fires EVERYTIME I return to the app from the background (the event handlers will be stacked every time a push notification to sent and fires all of them). As opposed to only executing that part of the callback code for push notifications that have come in from the background.
How do I know if the push notification came from the background or whilst app is running? cheers
Update:
Solved it.
If you check the call back object, you will find IsBackground as a property to check where the push notification came from.
Solution:
Check JSON object of callback for the isBackground boolean event.
If 1 it means that it was called from the background, if 0, this means that it wasn't.

Function is called too many times and retains old variable values

I currently have a table that is updated every time a user presses a button (handled using Backbone events).
Here is the event that is fired every time the button is pressed:
add: function(ev) {
if($(ev.target).data("card-id")) {
this.card_array.push($(ev.target).data("card-id"));
current_deck.push($(ev.target).data("card-id"));
updateCurrentDeckTable();
} else {
alert("Couldn't add the card. Please wait a few seconds before trying again.");
}
console.log(this.card_array);
console.log(current_deck);
}
updateCurrentDeckTable is defined as so:
function updateCurrentDeckTable() {
console.log(current_deck);
var content = "";
$.each(current_deck, function(i, cardId) {
console.log("Index: "+i+" || Card ID: "+cardId);
var M_Card = Parse.Object.extend("Card");
var M_CardQuery = new Parse.Query(M_Card);
M_CardQuery.get(cardId, {
success: function(m_card) {
console.log("Got "+m_card.get("cardTitle"));
content += "<tr>";
content += "<td>"+m_card.get("objectiveNumber")+"</td>";
content += "<td>"+m_card.get("cardTitle")+"</td>";
if (m_card.get("cardAffiliation") == null) {
content += "<td>-</td>";
} else {
content += "<td>"+m_card.get("cardAffiliation")+"</td>";
}
content += "<td><a>Details</a></td>";
content += "</tr>";
console.log("Content: "+content);
$('#deck-table tbody').append(content);
},
error: function() {
alert("Error.");
}
});
});
}
Now, the first time the user presses the button, everything works just fine. However, on the second press, more than one row is added to the table. Further, the content variable seems to keep it's old values. Shouldn't it reset to "" every time the function is called?
Does anyone have any idea what's happening? If you need more information, please ask.
Why oh why are you passing data using a global current_deck variable?
Each time you enter the updateCurrentDeckTable branch of your add method:
if($(ev.target).data("card-id")) {
this.card_array.push($(ev.target).data("card-id"));
current_deck.push($(ev.target).data("card-id"));
updateCurrentDeckTable();
}
You're adding another entry to the global current_deck and then updateCurrentDeckTable iterates over that array:
$.each(current_deck, function(i, cardId) { ...
I don't see anything that clears out current_deck so it will just keep growing. That would explain the odd behavior you're describing.
The solution would be to stop using a global for current_deck, just pass it around as an argument and clean it up as needed.

Categories

Resources