AngularJS - Weird error with sending and deleting JSON data from cache in while loop? - json

The loop is behaving strange where the alerts are firing out of order and the JSON data is being sent all at the same exact time. I do not understand why this is happening at all. I have been struggling with this for too long now and any help would be insanely appreciated!
Submitting with 3 cached JSON objects, the sequence goes:
Alert "should be second"
Alert "should be second"
Alert "should be second"
Alert "{#xmlns:ns3":"url}"
Alert "should be first"
Alert "0posted"
Then successfully sends all three JSON objects to the database at the same time.
The cachePostCount is now set to zero
app.controller('FormCtrl', function($scope, $filter, $window, getData, Post, randomString) {
// Get all posts
$scope.posts = Post.query();
// Our form data for creating a new post with ng-model
$scope.postData = {};
$scope.$on('updateImage', function () {
$scope.postData.attachment = getData.image;
});
$scope.postData.userid = "Mango Farmer";
$scope.postData.uuid = randomString(32); //$scope.genUUID();
$scope.$on('updateGPS', function () {
$scope.postData.gps = getData.gps;
});
$scope.postData.devicedate = $filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
$scope.newPost = function() {
var post = new Post($scope.postData);
var postCount = window.localStorage.getItem("cachedPostCount");
if(typeof postCount == 'undefined' || postCount == null){
postCount = 1;
window.localStorage.setItem("cachedPostCount", postCount);
}
else {
postCount ++;
window.localStorage.setItem("cachedPostCount", postCount);
}
window.localStorage.setItem("post" + postCount, JSON.stringify(post));
while (postCount > 0) {
var curCacheObj = new Post(JSON.parse(window.localStorage.getItem("post" + postCount) || '{}'));
curCacheObj.$save().then(function(response) {
var servResponse = JSON.stringify(response);
alert(servResponse);
if (servResponse.indexOf("#xmlns:ns3") > -1) {
alert("should be first");
window.localStorage.removeItem("post" + postCount);
alert(window.localStorage.getItem("cachedPostCount") + "posted");
$window.location.href = 'success.html';
}
else {
alert("Unable to post at this time!");
}
});
alert("should be second");
postCount --;
window.localStorage.setItem("cachedPostCount", postCount);
}
};

$save() is an asynchronous operation and is guaranteed to not happen until after the next tick in the event loop, which will occur after alert("should be second"); occurs. You should place this alert (and any other logic) that relies on that ordering inside the then() function or chain on another then() function and put it in there instead, like so:
curCacheObj.$save().then(function(response) {
var servResponse = JSON.stringify(response);
alert(servResponse);
if (servResponse.indexOf("#xmlns:ns3") > -1) {
alert("should be first");
window.localStorage.removeItem("post" + postCount);
alert(window.localStorage.getItem("cachedPostCount") + "posted");
$window.location.href = 'success.html';
}
else {
alert("Unable to post at this time!");
}
}).then(function() {
alert("should be second");
postCount --;
window.localStorage.setItem("cachedPostCount", postCount);
});

The problem was that .$save() does not like while loops (maybe because it is an asynchronous function as mentioned previously). I recreated the effect of a while loop with a function using an if statement that will fire the function again if the cached postCount still has data as follows:
$scope.submitAndClearCache = function() {
var postCount = window.localStorage.getItem("localPostCount");
var curCacheObj = new Post(JSON.parse(window.localStorage.getItem("post" + postCount) || '{}'));
if (postCount != 0) {
curCacheObj.$save().then(function(response) {
alert(response);
alert("Post " + postCount + " sent!");
}).then(function() {
postCount --;
window.localStorage.setItem("localPostCount", postCount);
postCount = window.localStorage.getItem("localPostCount");
$scope.submitAndClearCache();
});
}
};
$scope.addCachePost = function() {
var frmData = new Post($scope.postData);
var postCount = window.localStorage.getItem("localPostCount");
postCount ++;
window.localStorage.setItem("localPostCount", postCount);
window.localStorage.setItem("post" + postCount, JSON.stringify(frmData));
};
This technique works, it just seems weird.

Related

Node.js JSON Encode – Array Output Is Empty

I wroted this code to get a value from a database column to output with in JSON array. I succeeded to get it on the browser console, so I tried it with another value and used the same format to the code to passing it from my class file to the router app.post on the other file. I can see it on the terminal when I use console.log, but I can't see the output in the browser response, so what's wrong?
The code that successfully prints output:
auth.js, router part
app.post('/dispalymove', function (req, res, next) {
var lMove="";
if(req.body.MoveString !== null){
Move.setMoveUserId(req.user.id);
Move.setMoveString(req.body.MoveString);
lMove = a.getLastMove(req.user.GameId,function(move){
console.log("Return from display move:",move);
});
}
var output = {"msg":lMove, "loggedin":"true"};
res.send(JSON.stringify(output));
});
The function that I call on move.js file:
getLastMove(id,callback){
var MoveRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(MoveRequest, function(err,rows, result) {
if (rows.length == 0) {
return callback ("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
var move = rows[i].MoveString;
if (rows[i].GameId == id){
callback(move);
}
}
}
});
var move="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
return move;
}
The response on the browser console when the output is successful:
msg:"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
loggedin:"true"
the outputting code that have the problem
app.post('/getcolor', function (req, res, next) {
var lCol="";
if(req.body.MoveString !== null){
Move.setMoveUserId(req.user.id);
lCol = a.getColor(req.user.id,function(col){
console.log("Return from getcolor:",col)
//the the value that i get on terminal "Return from getcolor:white"
});
}
var output = {"msg":lCol, "loggedin":"true"};
res.send(JSON.stringify(output));
});
The function that I call from the other file:
getColor(id,callback){
var ColRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(ColRequest, function(err,rows, result) {
if (rows.length == 0) {
return callback ("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
var col = rows[i].GameColor;
if (rows[i].id == id){
callback(col);
}
}
}
});
var col="";
return callback(col);
}
The value that I get on my browser console response output just
loggedin:"true"
that should be like that
msg:"white"
loggedin:"true"
I tried to write this code with php
to post getcolor like that
session_start();
include "../classes/move.php";
$lCol="";
if(isset($_POST['MoveString'])){
$move = new move();
$move->setMoveUserId($_SESSION['UserId']);
$lCol=$move->getColor($_SESSION['UserId']);
}
$output = array("msg"=>"$lCol", "loggedin"=>"true");
echo json_encode($output);
and the function that i call
public function getColor($id){
include "../../connectToDB.php";
$ColRequest=$_db->query("SELECT * FROM users ORDER BY UserId");
$existCount = $ColRequest->rowCount();
if ($existCount == 0) { // evaluate the count
return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
}
if ($existCount > 0) {
while($row = $ColRequest->fetch(PDO::FETCH_ASSOC)){
$userID = $row["UserId"];
$col = $row["GameColor"];
if($userID == $id) {
return $col;
}
}
}
$col="";
return $col;
}
and the output was that on browser console responses
msg:"white"
loggedin:"true"
This is because of lCol = a.getColor(req.user.id,function(col):
lCol is undefined here because getColor returns nothing, it expects a callback and gives you a value in this callback (while getLastMove in the contrary does return something). Try with :
app.post('/getcolor', function (req, res, next) {
var lCol = "";
if (req.body.MoveString !== null) {
Move.setMoveUserId(req.user.id);
// lCol = <=== useless because a.getcolor returns nothing
a.getColor(req.user.id, function (col) {
console.log("Return from getcolor:", col)
//the the value that i get on terminal "Return from getcolor:white"
res.json({"msg": col, "loggedin": "true"}); // <=== here you have a defined lCol
});
} else {
var output = {"msg": lCol, "loggedin": "true"}; // <=== here lCol always equals ""
res.json(output);
}
// var output = {"msg": lCol, "loggedin": "true"}; // <=== here lCol always equals undefined (when req.body.MoveString !== null)
// res.send(JSON.stringify(output));
});
Edit: in the getColor and getLastMove function you sould not return anthing: just use the callback: because connection.query is asynchronous any return will be invalid; In getColor your are doing
var col="";
return callback(col); so you will always have a "" response. Beware: do not call a callback function several times when it ends to a server response (you can't send multiple responses for one request): your callback calls are in a loop, they should not, just call it once.

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};

Why can't my html5 class find my observable array contents?

Thanks in advance for any help. I have spent a couple of weeks scouring the web for some insight. I have been developing code for over 50 years but I am a fairly new JavaScript, HTML, knockout. From what I see, this will be great if I can figure out how to make it work. The example given below is only one of the many things I have tried. Please advise.
I have defined two variables as observables, one computed observable, and one observableArray in my view model. Within the document.ready function, I make an Ajax call which returns a json in object notation. ( I checked it in the debugger). When my HTML page displays the observables and computed observables show up properly. The
observable array generates an error (see below) and then displays data obtained from only the first row returned from Ajax. (two were returned).
How do I adjust my code so that all the rows in the Ajax data are shown in the displayed HTML?
Here is the error message that I get:
Uncaught ReferenceError: Unable to process binding "foreach: function (){return cartItems }"
Message: Unable to process binding "text: function (){return itemSubTotal() }"
Message: itemSubTotal is not defined (19:41:39:172 | error, javascript)
Here is my global data for the view model:
var cartDB = "";
var totalPrice = "100";
var cartItems = new Array;
Here is the view model:
var ViewModel =function (){
// direct items ==
this.cartDB = ko.observable(cartDB);
// array itesm
// this.cartItems = ko.observableArray(cartItems);
this.cartItems = ko.mapping.fromJS(cartItems);
//for (var n = 1;n++;n<cartItems.length){ this.cartItems.push(cartItem[n]);}
// computed items
this.totalPriceSv = ko.computed(function(){
return "Total Price*=" + centsToDollars(totalPrice);// todo fix
} ,this);//end totalSvPrice
};// end ViewModel
The data is obtained from the following routine which calls on Ajax.This routine is called once from within document.ready and obtains the expected data on the success callback.
function databaseCart(commandInput, cartDBInput, cartPidInput,logPhpInput) {
var postData = new Array();
postData[0] = commandInput;
postData[1] = cartDBInput;
postData[2] = cartPidInput;
postData[3] = logPhpInput; //debug log on php side
data = null; //for return values
$.ajax({
type: "GET",
url: 'ww_CartProcess.php', //the script to call to get data
data: {data: postData},
dataType: 'json',
success: function(data) {
cartItems = data;
debug = 0;
},
complete: function(data) {
ko.applyBindings(new ViewModel);
return TRUE;
},
error: function(x, e) {//this is the error function for ajax
var xErr = x;
var eErr = e;
ajaxErrorProcessing(xErr, eErr, "addToCart", postData);
}
});
}// end databasecart
Here is the HTML 5 snippet.
<div>
<h1 id="cartTitle">Cart Number: <span data-bind="text: cartDB"> </h1>
<div class ="boxCartItem" data-bind="foreach:cartItems" >
<div class ="boxItemTitle">
<h2 data-bind="text: title()"></h2>
</div><!--boxItemTitle-->
<div class ="cartItemBottom"></div>
</div ><!--class ="boxCartItem"-->
My thanks to the commenters. I still do not know how to add an element to all item rows in an observable array, but this problem was caused by not having the item listed defined. Clue> When multiple errors are presented it is sometimes ( and maybe always) good to work from the bottom up.
The problem can be better stated as : Given a 2 x 17 array (2 rows and 17 columns of independent vars)create an observableArray that contains 2 rows and 17 plus columns consisting of the 17 independent variables (can only be changed in the database or by limited user input) augmented with a large number of computed functions .
1.0 I created an orderModel which contained the ko.computed(functions() for each dependent variable.
function rowOrder(data) {
var self = this;
var model = ko.mapping.fromJS(data, {}, self);
model.imagePathSv = ko.computed(function() {
var category = self.category();
var imageName = self.imageName();
var sv ="";
var sv = "products\\" +category+"\\" + imageName;
return sv;
});//end model.imagePathSv
//original offer
model.origNumValidate = ko.computed(function() {
ans = self.origNum();
if (ans < 0 | ans > 1) {
alert("\
Only onw Original can be pruchased");
ans = 1;
}
self.origNum(ans);
return ans;
});//originalNumValidate
model.origNumLabel = ko.computed(function() {
var sv = "Original..." + centsToDollars(self.origCost());
return sv;
});//end model.origNumLabel
model.origMattedShow = ko.computed(function() {
if (self.origMattedCost() > 0) {
return true;
}
else {
return false;
}
});
model.origMattedLabel = ko.computed(function() {
var sv = "Matting...." + centsToDollars(self.origMattedCost());
return sv;
});
model.origFramedShow = ko.computed(function() {
if (self.origFramedCost() > 0) {
return true;
}
else {
return false;
}
});
model.origFramedLabel = ko.computed(function() {
var sv = "Framing...." + centsToDollars(self.origFramedCost());
return sv;
});
//reproductons offer
model.reproNumValidate = ko.computed(function() {
ans = self.reproNum();
self.reproNum(ans);
return ans;
});
model.reproNumLabel = ko.computed(function() {
var sv = "Reproductions." + centsToDollars(self.reproCost()) + " each";
return sv;
});//end model.reproNumLabel
model.reproMattedShow = ko.computed(function() {
if (self.reproMattedCost() > 0) {
return true;
}
else {
return false;
}
});
model.reproMatted = ko.observable(true);
model.reproMattedLabel = ko.computed(function() {
var sv ="Matting...." +centsToDollars(self.reproMattedCost());
return sv;
});
model.reproFramedShow = ko.computed(function(){
if(self.reproFramedCost()>0){return true;}
else {return false;}
});
model.reproFramed = ko.observable(true);
model.reproFramedLabel = ko.computed(function() {
var sv ="Framing...." +centsToDollars(self.reproFramedCost());
return sv;
});
//pricing subTotals
model.productsSubTotal = ko.computed(function() {
var ans =self.origNum() * self.origCost() + self.reproNum() * self.reproCost();
return ans;
});//end model.productsSubTotal
model.productsSubTotalSv = ko.computed(function() {
return "Products.." +centsToDollars(model.productsSubTotal());
return ans;
});//end model.productsSubTotal
model.mattingSubTotal = ko.computed(function() {
return self.origNum() * self.origMattedCost() + self.reproNum() * self.reproMattedCost();
});//end model.mattingSubTotal
model.mattingSubTotalSv = ko.computed(function() {
return "Matting...." +centsToDollars(model.mattingSubTotal());
});//end model.mattingSubTotal
model.framingSubTotal = ko.computed(function() {
return self.origNum() * self.origFramedCost() + self.reproNum() * self.reproFramedCost();
});//end model.framingSubTotal
model.framingSubTotalSv = ko.computed(function() {
return "Framing...." +centsToDollars(model.framingSubTotal());
});//end model.productsSubTotal
model.rowSubTotal = ko.computed(function() {
return model.productsSubTotal() +model.mattingSubTotal() + model.framingSubTotal();
});//end model.rowsSubTotal
model.rowSubTotalSv = ko.computed(function() {
return "Item Subtotal.." +centsToDollars(model.rowSubTotal());
});//end model.productsSubTotal
};// END rowOrder
2.0 I created a mapping variable as follows:
var mapping = {
create: function(options) {
return new rowOrder(options.data);
}
};
3,0 I created a View Model as follows:
function ViewModel() {
// direct items for whole page
var self = this;
this.cartId = ko.observable(cartDB);
this.cartIdSv = ko.computed(function() {
var sv = "Cart Number: "+ self.cartId();
return sv;
},this);//
this.totalPrice = ko.computed(function() {//to DO COMPUTE
var int = 10000;
return int;
},this);
this.totalPriceSv = ko.computed(function(){
return "Total Price*: " + centsToDollars(this.totalPrice());
},this);
// by row items
this.cartItems = ko.mapping.fromJS(cartItems, mapping);
}// end ViewModel
4.0 In the success call back from ajax :
success: function(data) {
cartItems = data;
ViewModel();
5.0 I put the ko.apply.bindings(new ViewModel) in the ajax complete callback.
The result was that my rather involved page came up as expected with the computed values initially set.
I am still working on how to update this page. I have not been able to get my code to recompute the computed variables when the user clicks or unclicks a checkbox.
I could not have done this without suggestions from the stackOverflow group. Thanks to you all for the posts that I found all over the google.

Windows 8 Javascript Promises

I have the following function:
function pickContacts() {
var output = "";
// Create the picker
var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
picker.commitButtonText = "Select";
var emailsPromise = new WinJS.Promise(function () {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
});
return emailsPromise;
};
This gets me a list of e-mail addresses from selected contacts. So next I want to use that; here's my code:
document.getElementById("findEmail").addEventListener("click", function () {
var emailAdd = document.getElementById("email");
pickContacts().done(function (emails) {
emailDets.value = emails;
});
});
But I'm not getting the return value from pickContacts (which I've determined is actually returned). I'm guessing that there's something wrong with the way I'm handling the returned promise, but I can't seem to debug it (trying to step into it just exits the function).
What am I doing wrong?
You don't need to create a new promise--just return the promise from pickMultipleContactsAsync.then. The promises spec says that the return value from .then is another promise that's fulfilled when your completed handler finishes, and the fulfillment value is the return value of the completed handler. So you can just do this:
return picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
The other way works, but just creates yet another promise that isn't needed, and makes your code a little more complex.
You'll have to pass the completed callback as a parameter of your promise function and then call it with the results you want to pass. Esseintially:
var emailsPromise = new WinJS.Promise(function () {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
});
becomes:
var emailsPromise = new WinJS.Promise(function (complete, error, progress) {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
complete(output);
} else {
complete("");
}
});
});

jquery cookies for different countries link

I am trying to do cookie stuff in jquery
but it not getting implemented can you guys fix my problem
html code
<a rel="en_CA" class="selectorCountries marginUnitedStates locale-link" href="http://www.teslamotors.com/en_CA">united states</a>
<a rel="en_US" class="selectorCountries marginSecondCountry locale-link" href="http://www.teslamotors.com/en_CA">canada</a>
<a rel="en_BE" class="selectorCountries marginCanadaFrench locale-link" href="http://www.teslamotors.com/en_BE">canada(french)</a>
i am providing my js code below
http://jsfiddle.net/SSMX4/76/
when i click the different country links in the pop up it should act similar to this site
http://www.teslamotors.com/it_CH
$('.locale-link').click(function(){
var desired_locale = $(this).attr('rel');
createCookie('desired-locale',desired_locale,360);
createCookie('buy_flow_locale',desired_locale,360);
closeSelector('disappear');
})
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
function checkCookie(){
var cookie_locale = readCookie('desired-locale');
var show_blip_count = readCookie('show_blip_count');
var tesla_locale = 'en_US'; //default to US
var path = window.location.pathname;
// debug.log("path = " + path);
var parsed_url = parseURL(window.location.href);
var path_array = parsed_url.segments;
var path_length = path_array.length
var locale_path_index = -1;
var locale_in_path = false;
var locales = ['en_AT', 'en_AU', 'en_BE', 'en_CA',
'en_CH', 'de_DE', 'en_DK', 'en_GB',
'en_HK', 'en_EU', 'jp', 'nl_NL',
'en_US', 'it_IT', 'fr_FR', 'no_NO']
// see if we are on a locale path
$.each(locales, function(index, value){
locale_path_index = $.inArray(value, path_array);
if (locale_path_index != -1) {
tesla_locale = value == 'jp' ? 'ja_JP':value;
locale_in_path = true;
}
});
// debug.log('tesla_locale = ' + tesla_locale);
cookie_locale = (cookie_locale == null || cookie_locale == 'null') ? false:cookie_locale;
// Only do the js redirect on the static homepage.
if ((path_length == 1) && (locale_in_path || path == '/')) {
debug.log("path in redirect section = " + path);
if (cookie_locale && (cookie_locale != tesla_locale)) {
// debug.log('Redirecting to cookie_locale...');
var path_base = '';
switch (cookie_locale){
case 'en_US':
path_base = path_length > 1 ? path_base:'/';
break;
case 'ja_JP':
path_base = '/jp'
break;
default:
path_base = '/' + cookie_locale;
}
path_array = locale_in_path != -1 ? path_array.slice(locale_in_path):path_array;
path_array.unshift(path_base);
window.location.href = path_array.join('/');
}
}
// only do the ajax call if we don't have a cookie
if (!cookie_locale) {
// debug.log('doing the cookie check for locale...')
cookie_locale = 'null';
var get_data = {cookie:cookie_locale, page:path, t_locale:tesla_locale};
var query_country_string = parsed_url.query != '' ? parsed_url.query.split('='):false;
var query_country = query_country_string ? (query_country_string.slice(0,1) == '?country' ? query_country_string.slice(-1):false):false;
if (query_country) {
get_data.query_country = query_country;
}
$.ajax({
url:'/check_locale',
data:get_data,
cache: false,
dataType: "json",
success: function(data){
var ip_locale = data.locale;
var market = data.market;
var new_locale_link = $('#locale_pop #locale_link');
if (data.show_blip && show_blip_count < 3) {
setTimeout(function(){
$('#locale_msg').text(data.locale_msg);
$('#locale_welcome').text(data.locale_welcome);
new_locale_link[0].href = data.new_path;
new_locale_link.text(data.locale_link);
new_locale_link.attr('rel', data.locale);
if (!new_locale_link.hasClass(data.locale)) {
new_locale_link.addClass(data.locale);
}
$('#locale_pop').slideDown('slow', function(){
var hide_blip = setTimeout(function(){
$('#locale_pop').slideUp('slow', function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',1,360);
}
else if (show_blip_count < 3 ) {
var b_count = show_blip_count;
b_count ++;
eraseCookie('show_blip_count');
createCookie('show_blip_count',b_count,360);
}
});
},10000);
$('#locale_pop').hover(function(){
clearTimeout(hide_blip);
},function(){
setTimeout(function(){$('#locale_pop').slideUp();},10000);
});
});
},1000);
}
}
});
}
This will help you ALOT!
jQuery Cookie Plugin
I use this all the time. Very simple to learn. Has all the necessary cookie functions built-in and allows you to use a tiny amount of code to create your cookies, delete them, make them expire, etc.
Let me know if you have any questions on how to use (although the DOCS have a decent amount of instruction).