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;
}
Related
I tried to rewrite my tests in Page Object style but something goes wrong.
I use Class Tab and this is a part of my code:
var World = require('../support/world.js');
const isAllAjaxRequests = require('../scripts/util').isAllAjaxRequests;
const isElementLocatedAndVisible = require('../scripts/util').isElementLocatedAndVisible;
module.exports.Tab = class Tab {
constructor(data) {
this.name = "Base";
this.locators = {
'nextStepIsLocked': {xpath: '//md-tab-item[#aria-selected="true"]//div[#class="cc-status red"]'},
'isActiveTab': {xpath: '//md-tab-item[#aria-selected="true"]//span[text()="'+ data + '"]'}
}
}
waitForElement(bySelector) {
var driver = World.getDriver();
var self = this;
//var bySelector = self.locators[bySelector];
return driver.wait(isAllAjaxRequests(driver), waitTimeOut).then(() => {
//console.log(bySelector)
return driver.wait(isElementLocatedAndVisible(bySelector), waitTimeOut);
});
}
tabIsOpen(tabName) {
var driver = World.getDriver();
var self = this;
var bySelector = By.xpath('//md-tab-item[#aria-selected="true"]//span[text()="'+ tabName + '"]');
return self.waitForElement(bySelector);
}
}
Code in util:
exports.isElementLocatedAndVisible = function isElementLocatedAndVisible(driver, bySelector) {
return new Condition('element is located and visible', function(driver) {
console.log(bySelector)
return driver.findElements(bySelector).then((arr) => {
if (arr.length > 0) {
return arr[0].isDisplayed();
}
else {
return false;
}
});
});
};
I tried to use is in my test:
this.Then(/^Tab "([^"]*)" is open$/, function (tabName) {
this.createTab(tabName);
//var bySelector = tab.getLocator(isActiveTab);
return tab.tabIsOpen(tabName);
});
But I recieved an Invalid Locator error.
Via debug print I see thah I miss bySelector value when code go to exports.isElementLocatedAndVisible function. This is undefiened.
What I did wrong?
I suspect it is just missing of a parameter causing the issue.
In the following line:
return driver.wait(isElementLocatedAndVisible(bySelector), waitTimeOut);
add driver object as first argument and then bySelector, as follows:
return driver.wait(isElementLocatedAndVisible(driver, bySelector), waitTimeOut);
function is defined as follows:
function isElementLocatedAndVisible(driver, bySelector)
so, expecting driver object along with bySelector
Soo, I keep getting slammed with cautions from Chrome about how synchronous XmlHttpRequest calls are being deprecated, and I've decided to have a go at trying to convert my use-case over in order to keep up with this fad...
In this case, I have an ~9 year old JS object that has been used as the central (and exemplary) means of transporting data between the server and our web-based applications using synchronous XHR calls. I've created a chopped-down version to post here (by gutting out a lot of sanity, safety and syntax checking):
function GlobalData()
{
this.protocol = "https://";
this.adminPHP = "DataMgmt.php";
this.ajax = false;
this.sessionId = "123456789AB";
this.validSession = true;
this.baseLocation = "http://www.example.com/";
this.loadResult = null;
this.AjaxPrep = function()
{
this.ajax = false;
if (window.XMLHttpRequest) {
try { this.ajax = new XMLHttpRequest(); } catch(e) { this.ajax = false; } }
}
this.FetchData = function (strUrl)
{
if ((typeof strURL=='string') && (strURL.length > 0))
{
if (this.ajax === false)
{
this.AjaxPrep();
if (this.ajax === false) { alert('Unable to initialise AJAX!'); return ""; }
}
strURL = strURL.replace("http://",this.protocol); // We'll only ask for data from secure (encrypted-channel) locations...
if (strURL.indexOf(this.protocol) < 0) strURL = this.protocol + this.adminPHP + strURL;
strURL += ((strURL.indexOf('?')>= 0) ? '&' : '?') + 'dynamicdata=' + Math.floor(Math.random() * this.sessionId);
if (this.validSession) strURL += "&sessionId=" + this.sessionId;
this.ajax.open("GET", strURL, false);
this.ajax.send();
if (this.ajax.status==200) strResult = this.ajax.responseText;
else alert("There was an error attempting to communicate with the server!\r\n\r\n(" + this.ajax.status + ") " + strURL);
if (strResult == "result = \"No valid Session information was provided.\";")
{
alert('Your session is no longer valid!');
window.location.href = this.baseLocation;
}
}
else console.log('Invalid data was passed to the Global.FetchData() function. [Ajax.obj.js line 62]');
return strResult;
}
this.LoadData = function(strURL)
{
var s = this.FetchData(strURL);
if ((s.length>0) && (s.indexOf('unction adminPHP()')>0))
{
try
{
s += "\r\nGlobal.loadResult = new adminPHP();";
eval(s);
if ((typeof Global.loadResult=='object') && (typeof Global.loadResult.get=='function')) return Global.loadResult;
} catch(e) { Global.Log("[AjaxObj.js] Error on Line 112: " + e.message); }
}
if ( (typeof s=='string') && (s.trim().length<4) )
s = new (function() { this.rowCount = function() { return -1; }; this.success = false; });
return s;
}
}
var Global = new GlobalData();
This "Global" object is referenced literally hundreds of times across 10's of thousands of lines code as so:
// Sample data request...
var myData = Global.LoadData("?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc");
if ((myData.success && (myData.rowCount()>0))
{
// Do Stuff...
// (typically build and populate a form, input control
// or table with the data)
}
The server side API is designed to handle all of the myriad kinds of requests encountered, and, in each case, to perform whatever magic is necessary to return the data sought by the calling function. A sample of the plain-text response to a query follows (the API turns the result(s) from any SQL query into this format automatically; adjusting the fields and data to reflect the retrieved data on the fly; the sample data below has been anonymized;):
/* Sample return result (plain text) from server:
function adminPHP()
{
var base = new DataInterchangeBase();
this.success = true;
this.colName = function(idNo) { return base.colName(idNo); }
this.addRow = function(arrRow) { base.addRow(arrRow); }
this.get = function(cellId,rowId) { return base.getByAbsPos(cellId,rowId); }
this.getById = function(cellId,rowId) { return base.getByIdVal(cellId,rowId); }
this.colExists = function(colName) { return ((typeof colName=='string') && (colName.length>0)) ? base.findCellId(colName) : -1; }
base.addCols( [ 'id','email','firstName','lastName','namePrefix','nameSuffix','phoneNbr','companyName' ] );
this.id = function(rowId) { return base.getByAbsPos(0,rowId); }
this.email = function(rowId) { return base.getByAbsPos(1,rowId); }
this.firstName = function(rowId) { return base.getByAbsPos(2,rowId); }
this.lastName = function(rowId) { return base.getByAbsPos(3,rowId); }
this.longName = function(rowId) { return base.getByAbsPos(5,rowId); }
this.namePrefix = function(rowId) { return base.getByAbsPos(6,rowId); }
this.nameSuffix = function(rowId) { return base.getByAbsPos(7,rowId); }
this.companyName = function(rowId) { return base.getByAbsPos(13,rowId); }
base.addRow( [ "2","biff#nexuscons.com","biff","broccoli","Mr.","PhD","5557891234","Nexus Consulting",null ] );
base.addRow( [ "15","happy#daysrhere.uk","joseph","chromebottom","Mr.","","5554323456","Retirement Planning Co.",null ] );
base.addRow( [ "51","michael#sunrisetravel.com","mike","dolittle","Mr.","",""5552461357","SunRise Travel",null ] );
base.addRow( [ "54","info#lumoxchemical.au","patricia","foxtrot","Mrs,","","5559876543","Lumox Chem Supplies",null ] );
this.query = function() { return " SELECT `u`.* FROM `users` AS `u` WHERE (`deleted`=0) ORDER BY `u`.`lastName` ASC, `u`.`firstName` LIMIT 4"; }
this.url = function() { return "https://www.example.com/DataMgmt.php?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc&dynamicdata=13647037920&sessionId=123456789AB\"; }
this.rowCount = function() { return base.rows.length; }
this.colCount = function() { return base.cols.length; }
this.getBase = function() { return base; }
}
*/
In virtually every instance where this code is called, the calling function cannot perform its work until it receives all of the data from the request in the object form that it expects.
So, I've read a bunch of stuff about performing the asynchronous calls, and the necessity to invoke a call-back function that's notified when the data is ready, but I'm a loss as to figuring out a way to return the resultant data back to the original (calling) function that's waiting for it without having to visit every one of those hundreds of instances and make major changes in every one (i.e. change the calling code to expect a call-back function as the result instead of the expected data and act accordingly; times 100's of instances...)
Sooo, any guidance, help or suggestions on how to proceed would be greatly appreciated!
What I am trying to do is take an array within an object within an array within an object (I know my data structure is ridiculous, any help with that would be great also) and convert the last array into an object with a "key":"value". I'm using Angular 1.5.7 if there is anything in Angular that could help do this. I know that probably makes no sense. I couldn't figure out a way to say what I am trying to do clearly so let me show you:
I start with an object like this:
{"instructor":[{"instructor_emails":[ "test#test.com","tester#tester.com"]}]}
And I want it to be:
{"instructor":[{"instructor_emails":{ "email":"test#test.com","email":"tester#tester.com"}}]}
I tried a couple of things and the closest I found was:
instructor.instructor_emails.map(function(e) {
return { email: e };
});
But it doesn't quite do what I'm trying to do... Any thoughts?
This was correct all along (Thanks Alex)
instructor.instructor_emails.map(function(e) {
return { email: e };
});
Returns:
{instructor:[instructor_emails[{"email":"example1#example1.com",{"email":"example1#example1.com"}]]}
The data structure is still ridiculous but it will suffice for what I am trying to do
You should read up on Object-oriented programming for optimal data storage, particularly concerning classes. To transition between traditional OOP languages, like Java, to JavaScript you can use TypeScript.
Below is a snippet i created using TypeScript:
/// <reference path="definitions/jquery.d.ts" />
console.clear();
var Instructor = (function () {
function Instructor(name, emails) {
if (name === void 0) { name = ""; }
if (emails === void 0) { emails = []; }
this.name = name;
this.emails = emails;
}
Instructor.prototype.addEmail = function (email) {
if (email === void 0) { email = ""; }
//Run validation
if (email.length > 3) {
this.emails.push(email);
}
};
Instructor.prototype.getEmails = function (type) {
if (type === void 0) { type = "array"; }
var self = this;
type = type.toLowerCase();
var getEmails = {
string: function () {
return self.emails.join(" ");
},
object: function () {
return self.emails.map(function (e) {
return { email: e };
});
}
};
if (getEmails[type] === void 0) {
return this.emails;
}
else {
return getEmails[type]();
}
};
return Instructor;
}());
var instructors = [
new Instructor("Michael Bennet I", ["test#test.com", "tester#tester.com"]),
new Instructor("Michael Bennet II", ["test#test.com", "tester#tester.com"]),
];
console.log('array', instructors[0].getEmails());
console.log('object', instructors[0].getEmails("object"));
console.log('string', instructors[0].getEmails("String"));
/*
// This is TypeScript
class Instructor {
constructor(public name: string = "", public emails: string[] = []) {
}
public addEmail(email: string = "") {
//Run validation
if (email.length > 3) {
this.emails.push(email);
}
}
public getEmails(type: string = "array") {
var self = this;
type = type.toLowerCase();
var getEmails = {
string: function () {
return self.emails.join(" ");
},
object: function () {
return self.emails.map(function (e) {
return { email: e };
});
}
}
if (getEmails[type] === void 0) {
return this.emails;
} else {
return getEmails[type]();
}
}
}
var instructors: Instructor[] = [
new Instructor("Michael Bennet I", ["test#test.com", "tester#tester.com"]),
new Instructor("Michael Bennet II", ["test#test.com", "tester#tester.com"]),
];
console.log('array',instructors[0].getEmails());
console.log('object',instructors[0].getEmails("object"));
console.log('string',instructors[0].getEmails("String"));
<p>Object can have their own functions to "get" data they contain in unique ways.</p>
<p>This way, you can get the same data in several different ways</p>
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
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");
}
});
}