JavaScript if() case in CloudCode. - javascript

In this code im trying to get the Object for the caller of this method, using his unique username. If the object exists -> update it, of not -> create one.
However: my boolean value "found" is never changed. Even though, it must be changed after my Query. Because of this my if statement is never used and therefore no object created.
Does anyone know why?
To my knowledge its ok changing a global value from within a function.
Parse.Cloud.define("updateUserGeneral", function(request, response){
var UserGeneralObject = Parse.Object.extend("userGeneral");
var userGeneralNew = new UserGeneralObject();
var found = false;
var username = request.params.username;
var private_name = request.params.private_name;
var intentions = request.params.intentions;
var gender = request.params.gender;
var looking_gender = request.params.lookinggender;
var age = request.params.age;
var min_age = request.params.min_age;
var max_age = request.params.max_age;
var radius = request.params.radius;
var applyradius = request.params.applyradius;
var query2 = new Parse.Query("userGeneral");
query2.equalTo("username", username);
query2.first({
success: function(userGeneral){
if(userGeneral!=null){
found = true;
userGeneral.set("private_name", private_name);
userGeneral.set("intentions", intentions);
userGeneral.set("gender", gender);
userGeneral.set("lookinggender", looking_gender);
userGeneral.set("age", age);
userGeneral.set("max_age", max_age);
userGeneral.set("min_age", min_age);
userGeneral.set("radius", radius);
userGeneral.set("applyradius", applyradius );
userGeneral.save();
response.success("Succesfully saved userGeneral");
}else{
found = false;
}
},
error: function(error){
found = false;
}
});
if(found == false){
userGeneralNew.set("username", username);
userGeneralNew.set("private_name", private_name);
userGeneralNew.set("intentions", intentions);
userGeneralNew.set("gender", gender);
userGeneralNew.set("lookinggender", looking_gender);
userGeneralNew.set("age", age);
userGeneralNew.set("max_age", max_age);
userGeneralNew.set("min_age", min_age);
userGeneralNew.set("applyradius", applyradius);
userGeneralNew.set("radius", radius);
userGeneralNew.set("lookingForChat", 0);
userGeneralNew.set("lookingForInvitation", 1);
userGeneralNew.set("userHasChat", 0);
userGeneralNew.save(null, {
success: function () {
console.log("Save ok");
response.success("Succesfully saved userGeneral New");
},
error: function (error) {
console.log("Save failed");
response.error("Failed saving userGeneral New");
}
});
}
});

success: function(userGeneral){ is a callback function. In this case the code will most likely finish before you update the variable found. So the following code will run before the success function runs.
if(found == false){
userGeneralNew.set("username", username);
userGeneralNew.set("private_name", private_name);
userGeneralNew.set("intentions", intentions);
userGeneralNew.set("gender", gender);
userGeneralNew.set("lookinggender", looking_gender);
userGeneralNew.set("age", age);
userGeneralNew.set("max_age", max_age);
userGeneralNew.set("min_age", min_age);
userGeneralNew.set("applyradius", applyradius);
userGeneralNew.set("radius", radius);
userGeneralNew.set("lookingForChat", 0);
userGeneralNew.set("lookingForInvitation", 1);
userGeneralNew.set("userHasChat", 0);
userGeneralNew.save(null, {
success: function () {
console.log("Save ok");
response.success("Succesfully saved userGeneral New");
},
error: function (error) {
console.log("Save failed");
response.error("Failed saving userGeneral New");
}
});
}

Related

Can't use Angular $q library in Visual Studio (Apache cordova)

I need to use $q to wait until my async function has completed and then do something.
However I have tried injecting $q into my angular module as well as my angular functions and I am getting the message $q is undefined.
Can someone tell me how I can go about being able to use this in my code?
Here is the code for the module and the function I want to use $q in respectively
Module
var droidSync = angular.module('droidSync', ['ionic', 'ngRoute', 'ui.router']);
Controller and FunctionIn this case I want to wait for the results.forEach to finish then I want to hide my loading screen using $ionicLoading.hide()
droidSync.controller('mainController', function ($scope, $ionicLoading) {
$scope.syncContacts = function () {
//Display a loading screen while sync is in execution
$ionicLoading.show({
template: '<p>Syncing Contacts...</p><ion-spinner class="spinner-calm" icon="crescent"/>'
});
var table = AzureService.getTable('contact');
table.read().done(function (results) {
results.forEach(function (result) { //THIS NEEDS TO BE COMPLETE BEFORE HIDING LOAD SCREEN
console.log('result is', result);
// If the contact is flagged as deleted check if its on the device and delete it
if (result.isdeleted == true) {
var options = new ContactFindOptions();
options.filter = result.id;
options.multiple = false;
var fields = ["*"];
navigator.contacts.find(fields, findSuccess, findError, options);
function findSuccess(contact) {
if (contact.length > 0) {
console.log("inside the delete area:", contact);
var contactToDelete = navigator.contacts.create();
//It is safe to use contact[0] as there will only ever be one returned as AzureID is unique
contactToDelete.id = contact[0].id;
contactToDelete.rawId = contact[0].id;
console.log('we want to delete this', contactToDelete);
contactToDelete.remove();
console.log('Contact Deleted');
}
else {
console.log('Contact to delete not present on device. Checking next contact');
}
}
function findError() {
console.log('Contact search failed: Deleted Contact Search');
}
}
else {
//create a contact object to save or update
var emails = [];
var phoneNumbers = [];
var name = new ContactName();
var contactToUpdate = navigator.contacts.create();
contactToUpdate.note = result.id;
name.givenName = result.firstname;
name.familyName = result.lastname;
phoneNumbers[0] = new ContactField('mobile', result.mobilephone, true);
phoneNumbers[1] = new ContactField('home', result.homephone, false);
emails[0] = new ContactField('work', result.email, true);
contactToUpdate.name = name;
contactToUpdate.phoneNumbers = phoneNumbers;
contactToUpdate.emails = emails;
//Search for the contact on the device
var options = new ContactFindOptions();
options.filter = result.id;
options.multiple = false;
var fields = ["*"];
navigator.contacts.find(fields, foundSuccess, foundError, options);
function foundSuccess(contact) {
if (contact.length > 0) {
//The contact has been found on the device. Pass in ids for contact, emails and phone numbers to update.
console.log('object to update is object is', contact);
console.log('contact array length is ', contact.length);
contactToUpdate.id = contact[0].id;
contactToUpdate.rawId = contact[0].rawId;
contactToUpdate.phoneNumbers[0].id = contact[0].phoneNumbers[0].id;
contactToUpdate.phoneNumbers[1].id = contact[0].phoneNumbers[1].id;
contactToUpdate.emails[0].id = contact[0].emails[0].id;
console.log('about to save this', contactToUpdate);
contactToUpdate.save(upSuccess, upError);
function upSuccess() {
console.log('updated a contact!');
}
function upError(ContactError) {
console.log('error updating a contact!');
}
}
else {
//The contact does not exist on the device. Just save it.
console.log('non existent contact: ', contactToUpdate);
contactToUpdate.save(saveSuccess, SaveError);
function saveSuccess() {
console.log('saved a contact!');
}
function SaveError() {
console.log('error saving a contact!');
}
}
}
function foundError() {
console.log('Contact search failed: Undeleted Contact Search');
}
} // end else
})) // end forEach
}) // table.read()
}; // scope.syncContacts()
});
So i'd probably do something like this
This is completely untested code so take that for what you will
$q.all is what your going to want to look into
droidSync.controller('mainController', ["$scope", "$q", "$ionicLoading",
function ($scope, $q, $ionicLoading) {
var loop = function(result){
var deferred = $q.defer();
deferred.resolve(// your loop stuff);
return deferred.promise;
};
var loopingFunction = function(results){
var promises = [];
results.forEach(function(result){
promises.push(loop(result));
});
return $q.all(promises);
};
$scope.syncContacts = function () {
//Display a loading screen while sync is in execution
$ionicLoading.show({
template: '<p>Syncing Contacts...</p><ion-spinner class="spinner-calm" icon="crescent"/>'
});
var table = AzureService.getTable('contact');
table.read().done(function (results) {
loopingFunction(results).then(function(){
// do something after it finishes
$ionicLoading.hide()
});
});
};
}]);

Create an object upon a certain condition

How does one create an object in Javascript conditional upon a certain condition inside said object. For instance:
function User(email) {
this.email = email;
this.checkValid = function () {
// check email if not valid delete the object or return nothing
}
this.checkValid()
}
var user1 = new User("bob123#aol.com")
if not valid delete the object
Don't. Better, test the email address to be valid before trying to create the user.
or return nothing
You can't really. Returning nothing from a constructor is effectively quite impossible, except you throw an exception.
Use an extra factory function instead:
function isValidEmail(str) {
// http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/
return /.+#.+\..+/.test(str);
}
function User(email) {
// possible, but better don't do this:
// if (!isValidEmail(email)) throw new Error("Tried to create User with invalid email")
this.email = email;
}
User.prototype.checkValid = function () {
return isValidEmail(this.email);
};
User.create = function(email) {
if (isValidEmail(email))
return new User(email);
else
return null;
};
var user1 = User.create("bob123#aol.com")
if (user1)
this.checkValid() // true
function createUser(username, email)
{
if (email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig))
{
window[username] = new User(email);
return true;
}
else
{
return null;
}
}
function User(email)
{
this.email = email;
}
if (createUser("user1", "bob123#aol.com"))
{
document.write("User 1: " + user1.email + "<br />");
}
if (createUser("user2", "bob123aol.com"))
{
document.write("User 2: " + user2.email);
}
document.write(window['user1'] + "<br />");
document.write(window['user2']);
This will check if the user has a valid e-mail. If so create a global variable constructed from User, if not nothing is returned. You can of course replace the window (global scope) object with any other object.
function User(email) {
this.email = email;
this.check();
};
User.prototype.check = function() {
if (this.email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig)) {
console.log('Valid email');
} else {
console.log('Invalid email');
}
};
var user1 = new User("bob123#aol.com");
You could use try, catch
function User(email) {
this.email = email;
this.checkValid()
}
User.prototype.checkValid = function () {
var valid = false;
//or true if valid email
if(!valid) throw 'Not valid email';
}
try {
var user1 = new User("bob123#aol.com");
} catch(e) {
console.log(e);
}
But in my opinion a constructor should always create an object, so I would do something like this:
function User(email) {
this.email = email;
}
User.prototype.isValid = function () {
if (this.email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig)) {
return true;
}
return false;
}
var user1 = new User("bob123#aol.com");
if(!user1.isValid()){
user1 = null;
}

Javascript--Breeze Manager Not Detecting Changes

I'm using the EntityManager from Breeze for the API portion of data-binding. However, the EntityManager fails to track the changes. It will execute the code like it's supposed to but it never recognizes the changes. What's the issue? Please, refrain from saying anything that is not constructive or any personal attacks. We're here as professionals and scientists(i know i am). Here is my code:
Service:
(function () {
var serviceId = 'UWRLService';
angular.module('myApp')
.factory(serviceId, ['$q', 'breeze', 'logger', 'appSettings', UWRLService]);
// console.log('Initialized UWRL Service.js');
function UWRLService($q, breeze, logger, appSettings) {
// console.log('inside datacontext -- UWRLService');
// configure logging for this service
logger = logger.forSource(serviceId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
//Setup variables with common Breeze query classes
var entityQuery = breeze.EntityQuery;
// setup breeze entity manager
var serviceName = appSettings.apiUrl + '/breeze/Uwrl/';//Where the entire service is pointing to
var manager = new breeze.EntityManager(serviceName);
var entityStateChangeAction = breeze.EntityAction.EntityStateChange;
// expose methods
var service = {
getChangesCount: getChangesCount,
saveChanges: saveChanges,
rejectChanges: rejectChanges,
getDivisions: getDivisions,
getPools: getPools,
getRandomCust: getRandomCust
//createChangeFactorEntity: createChangeFactorEntity,
};
return service;
// FUNCTION DECLARATIONS
//Attaches a new entity to the Breeze repository
//Passes the name and an array of values to seed the entity with
//function createChangeFactorEntity(entityName, initialValues) {
// var newFactor = manager.createEntity(entityName, initialValues);
// return newFactor;
//}
function getRandomCust()
{
var query = breeze.EntityQuery.from('alpha')
.where('customerNumber', '==', 1);
return executeQuery(query, 'Alpha found!');
}
function getDivisions()
{
var query = breeze.EntityQuery
.from('Divisions');
//executeQuery([query name], [query title])
return executeQuery(query, 'Divisions Found');
}
function getPools()
{
var query = breeze.EntityQuery
.from('Pools');
return executeQuery(query, 'Pools Found');
}
//Saves changes and logs exceptions
function saveChanges() {
var hasChanges = manager.hasChanges();
console.log(hasChanges);
console.log(manager.getChanges());
return manager.saveChanges()
.then(saveSucceeded)
.catch(saveFailed);
function saveSucceeded(saveResult) {
logSuccess("# of items saved = " + saveResult.entities.length, null, true);
logger.log(saveResult);
}
function saveFailed(error) {
var reason = error.message;
var detail = error.detail;
if (error.entityErrors) {
//Do nothing
} else if (detail && detail.ExceptionType &&
detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
// Concurrency error
reason =
"Another user, perhaps the server, " +
"may have deleted one or all of the todos." +
" You may have to restart the app.";
} else {
reason = "Failed to save changes: " + reason +
" You may have to restart the app.";
}
logError(reason, error, true);
throw error; //Downstream: users know it has failed
}
}
//Discards changes in Breeze Manager
function rejectChanges() {
if (manager.hasChanges()) {
count = getChangesCount();
manager.rejectChanges();
logWarning('Discarded ' + count + ' pending changes(s)', null, true);
}
}
//Returns (Nth-1) index of Breeze manager getChanges array
function getChangesCount() {
var ents = manager.getEntities();
var changes = manager.getChanges();
if (changes.length > 0)
{
alert("Changes made: " + manager.getChanges().length);
}
return manager.getChanges().length;
}
//Query Execution w/ toasters(logger)
function executeQuery(query, entityType) {
var promise = manager.executeQuery(query).then(querySucceeded, queryFailed);
return promise;
function querySucceeded(response) {
logSuccess(entityType + " query was successful", null, true);
return response.results;
}
function queryFailed(response) {
var message = response.message || entityType + " query failed";
logError(message, response, true);
throw error;
}
}
};
})()
Controller (javascript):
(function () {
'use strict';
var controllerId = 'UWRLController';
// console.log('Initialized UWRLController');
//Last item in passed array is the Controller (specific)
angular.module('myApp').controller(controllerId,
['$scope', 'UWRLService', 'logger',
'$routeParams', 'allStatesService', UWRLController]);
function UWRLController($scope, UWRLService, logger, $routeParams, allStatesService) {
// console.log('inside UWRLController');
//Loggin Initialization
logger = logger.forSource(controllerId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
var uwrl = {};
$scope.uwrl = uwrl;
//Parameters we pass from Renewal Group Maintenance screen
//uwrl.PlanCode = $routeParams.PlanCode;
//uwrl.Contract = $routeParams.ContractNumber;
//uwrl.Mch = $routeParams.Mch;
//Functions in Javascript Controller
//[scope].[property] = [function name]
uwrl.saveChanges = save;
uwrl.discardChanges = discardChanges;
uwrl.changesCount = changesCount();
//uwrl.select = select;
init();//Initialize all customer related data for page
function init()
{
gettingDivisions();//Initialze getting data from Division's table through UWRL-service.js
getAllFiftyStates();
gettingPools();
gettingRandom();
}
function gettingRandom()
{
UWRLService.getRandomCust()
.then(function(alpha)
{
uwrl.alpha = alpha;
uwrl.beta = uwrl.alpha[0].customerName;
});
}
function gettingDivisions()
{
UWRLService.getDivisions()
.then(function (divisionNumber) {
uwrl.divisionNumber = divisionNumber;
});
}
function getAllFiftyStates()
{
allStatesService.getStates()
.then(function (allStates)
{
uwrl.allStates = allStates;
});
}
function gettingPools()
{
UWRLService.getPools()
.then(function (poolNumber)
{
uwrl.poolNumber = poolNumber;
});
}
//Clicking the Drop-down Button
//function select(change) {
// this.MchMcpPlanDesignId = change.MchMcpPlanDesign.MchMcpPlanDesignId;
// change.expanded = !change.expanded; //toggle back and forth
//}
////.then = [if] success
////.fail = failure
////.finally = always executed despite evaluated conditionals
//function getPlans() {//returns a promise
// uwrl.loadingPlans = true;
// UWRLService.getChangeFactors(uwrl.Mch, uwrl.Contract, uwrl.PlanCode)
// .then(function (deltaChangeFactor) {
// uwrl.deltaChangeFactor = deltaChangeFactor;
// }).finally(function () { uwrl.loadingPlans = false; });
//}
////Returns all data in ChangeFactorType table
//function getChangeFactorTypes() {
// UWRLService.getTypes().then(function (changeFactorTypes) {
// uwrl.changeFactorTypes = changeFactorTypes;
// });
//}
//Clicking on Save Button
function save() {
console.log('Save Button Clicked!');
//Validation -- checks for empty values
//if (uwrl.changeFactorType != null && uwrl.effectiveDate != null &&
// uwrl.changeFactorAmount != null) {
// //Adds a new Breeze Entity for ChangeFactor table in SQL database
// UWRLService.createChangeFactorEntity('ChangeFactor',
// {
// MchMcpPlanDesignId: this.MchMcpPlanDesignId,
// ChangeFactorType: uwrl.changeFactorType,
// EffectiveDate: uwrl.effectiveDate,
// ChangeFactorAmount: uwrl.changeFactorAmount
// });
//}
//Saves to Breeze Manager
//Must hit Art's ESB service -- to be researched
UWRLService.saveChanges();
}
//Gets rid of changes and logs it
function discardChanges() {
console.log('Discard Button Clicked!');
UWRLService.rejectChanges();
}
//Notifies user(s) of changes made that are
//either: savable, discardable
function changesCount() {
// console.log("Changes Made: " + UWRLService.getChangesCount)//for debugging purposes
return UWRLService.getChangesCount;
}
};
})();
The answer is to make sure to effect the model. For example: uwrl.alpha[0].customerName instead of urwl.beta

Cloud code on parse.com skipping a save

I'm trying to set up a game that allows playing with random players. The code below is supposed to create a GameMessage object for both paired players. To relate both objects as part of the same game, I've decided to save the objectId of of the game made for "firstplayer" in the field "otherside" for "secondplayer" and vice-versa. For some reason (perhaps the first save of firstplayer and secondplayer isn't done before the code attempts to retrieve the objectIds, meaning there are no objectIds to get?).
Short version: Why are the "otherside" values not saving?
Parse.Cloud.define("findpartner", function(request, response) {
var User = Parse.Object.extend("_User");
var user = new User();
var currentuser = Parse.User.current();
currentuser.set("searching", 0);
var query = new Parse.Query(User);
query.equalTo("searching", 1);
query.limit(50); //limit to at most 50 users
query.find({
success: function(objects) {
var amount = objects.length;
var indexNum = Math.floor((Math.random() * amount));
var newpartner = objects[indexNum];
if (amount > 0 && newpartner.id !=currentuser.id) {
newpartner.set("searching", 0);
var Firstplayer = Parse.Object.extend("GameMessages");
var firstplayer = new Firstplayer();
var Secondplayer = Parse.Object.extend("GameMessages");
var secondplayer = new Secondplayer();
firstplayer.set("sender", currentuser.id);
firstplayer.set("receiver", newpartner.id);
firstplayer.set("sent",0);
firstplayer.set("received",0);
firstplayer.set("receiverName", newpartner.getUsername());
secondplayer.set("sender", newpartner.id);
secondplayer.set("receiver", currentuser.id);
secondplayer.set("sent",0);
secondplayer.set("received",0);
secondplayer.set("receiverName", currentuser.getUsername());
firstplayer.save().then(function(secondplayer){ <<<
return secondplayer.save(); <<<
}).then(function(firstplayer_update) { <<<
return firstplayer.save({ otherside: secondplayer.id}); <<<
}).then(function(secondplayer_update){ <<<
return secondplayer.save({ otherside: firstplayer.id}); <<<
});
newpartner.save(null, {useMasterKey: true});
}
else {
currentuser.set("searching", 1);
}
currentuser.save();
response.success(amount);
},
error: function(error) {
alert("Error: " + error.code = " " + error.message);
}
});
});
I added arrows to show where the "otherside" is. They're not in the actual code. I do not doubt the code has mistakes though, I do not know javascript. I wrote it solely by studying the parse.com documentation.
I'm not convinced that it makes sense to create these 2 independent messages and link them together, but I won't let that stand in the way of getting this working. This isn't tested, but I've refactored your code and think you should try to glean a few things from it.
// Set this up once, outside of your function, and use it everywhere
var GameMessage = Parse.Object.extend("GameMessages");
Parse.Cloud.define("findpartner", function(request, response) {
// Code defensively, make sure this function requires a user be logged in.
if (!request.user) {
console.log("non-user called findpartner");
return response.error("Unauthorized.");
}
// Get the user who called the function
var user = request.user;
// The end response is a number, apparently
var result = 0;
// The target player
var targetPlayer;
// The two messages that will be used if a match is found
var firstmsg = new GameMessage();
var secondmsg = new GameMessage();
// Create a Users query
var query = new Parse.Query(Parse.User);
query.equalTo("searching", 1);
query.notEqualTo("objectId", user.id);
query.limit(50);
// Remove public access to Find operations for Users in the Data Browser
// Use the master key to query, and use promise syntax.
query.find({ useMasterKey: true }).then(function(objects) {
result = objects.length;
// If no users were found searching, mark the user as searching and save
if (result == 0) {
user.set('searching', 1);
// Return the save promise
return user.save(null, { useMasterKey: true });
}
// Pick a random user out of the response
var indexNum = Math.floor((Math.random() * objects.length));
var targetPlayer = objects[indexNum];
// Set that user to no longer be searching and save
targetPlayer.set("searching", 0);
return targetPlayer.save(null, { useMasterKey: true }).then(function() {
firstmsg.set("sender", user.id);
firstmsg.set("receiver", targetPlayer.id);
firstmsg.set("sent", 0);
firstmsg.set("received", 0);
firstmsg.set("receiverName", targetPlayer.getUsername());
secondmsg.set("sender", targetPlayer.id);
secondmsg.set("receiver", user.id);
secondmsg.set("sent", 0);
secondmsg.set("received", 0);
secondmsg.set("receiverName", user.getUsername());
// Return the promise result of saving both messages
return Parse.Object.saveAll([firstmsg, secondmsg], { useMasterKey: true });
}).then(function(messages) {
// Set the pointers to reference each other
firstmsg.set("otherside", secondmsg.id);
secondmsg.set("otherside", firstmsg.id);
// Return the promise result of saving both messages, again
return Parse.Object.saveAll([firstmsg, secondmsg], { useMasterKey: true });
});
}).then(function() {
// All the stuff above has finished one way or the other, now we just need to
// send back the result. 0 if no match was made.
response.success(result);
}, function(error) {
response.error(error);
});
});
firstplayer.save();
secondplayer.save();
secondplayer.set("otherside",firstplayer.id); <<<
firstplayer.set("otherside",secondplayer.id); <<<
firstplayer.save();
secondplayer.save();
This is the part of code that you say not working. In parse doc you can see that .save() is a non blocking operation. Means the line firstplayer.save() goes immediately to next line(it wont block the thread for saving). So when you set id secondplayer.set("otherside",firstplayer.id) firstplayer.id is still undefined.
So if you want a synchronous logic, like save first_object then save second_object ,
you have to use call backs.
first_object.save({
success: function(saved_first_object) {
second_object.save({
success: function(saved_second_object) {
//process complete
},
failure: function(error){
}
})
},
failure: function(error) {
console.log(error);
}
})
You can also approach it using promises.
http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/
UPDATE: Based on question edit from OP trying promises
Try this
firstplayer.save()
.then(function(saved_firstPlayer){
firstplayer = saved_firstPlayer;
return secondplayer.save();
}).then(function(saved_secondplayer) {
secondplayer = saved_secondplayer;
return firstplayer.save({ otherside: secondplayer.id});
}).then(function(updated_firstplayer){
firstplayer = updated_firstplayer;
return secondplayer.save({ otherside: firstplayer.id});
}).then(function(updated_secondlayer){
secondplayer= update_secondplayer;
});

Failure when pass param between functions in js

when i launch my applicattion appears the next failure: "record is null or is not an object", appears in the next line " var record = context.record;" Somebody could explain or find the failure... i try to pass the var "mola" from beforeedit to the edit function...
My code is the next:
listeners: {
beforeedit:
function preditar(editor, e, eOpts, mola) {
var grid = Ext.getCmp('gridTabla'); // or e.grid
var hoy = new Date();
dia = hoy.getDate();
if(dia<10)
{
dia=String("0"+dia);
}
mes = hoy.getMonth();
if(mes<10)
{
mes=String("0"+mes);
}
anio= hoy.getFullYear();
fecha_actual = String(anio+""+mes+""+dia);
//alert(fecha_actual);
var mola = e.record.data.ESTLOT;
//alert(mola);
editar(mola);
if (e.record.data.ESTLOT === '02') {
if (e.record.data.FECMOD === fecha_actual)
{
e.cancel = false; //permite
}
else{
e.cancel = true; //mo permite
}
} else
{
e.cancel = false; //permite
}
},
edit:
function editar(e, context, mola){
var record = context.record;
var recordData = record.getData();
var mola2= mola;
alert(mola2);
recordData.Funcionalidad = 'Modificar';
//alert(JSON.stringify(recordData));
Ext.Ajax.request({
url: 'http://localhost:8080/MyMaver/ServletTablaLotes',
method: 'POST',
// merge row data with other params
params: recordData
});
}
}
});
You are calling the function with
editar(mola);
But the function is defined as:
editar(e, context, mola)
So the function only receives the e parameter and the others are set to undefined.
the problem is not the mola variable but e.record. As your error message states the variable e either does not contain an object record or e.record is null. Try to console.log(e) to inspect your variable e further.

Categories

Resources