Hi,
I'm trying, in a loop, to check if a model (in fact, only its attribute "name" matters) exists in a collection, and then add it to the collection in the case where it doesn't exist. But, it seems that this part of code:
var match = _.find(myCities.models, function(myCity) { return myCity == myCity;Doesn't work properly...
This is my complete code:
var url = "http://myURL/myFile.php"; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { // this function is called when data is returned from the server and available for use // this.responseText holds the raw text return of the message (used for text/JSON) // this.responseXML holds any returned XML (including SOAP) // this.responseData holds any returned binary data Ti.API.debug(this.responseText); var myTable = JSON.parse(this.responseText); var myCities = Alloy.createCollection('cities'); for(var i= 0; i < myTable.cities.length; i++) { var myCity = myTable.cities[i].nom_commune; var match = _.find(myCities.models, function(myCity) { return myCity == myCity; }); if (match == 'undefined') { var city = Alloy.createModel('cities', {name : myCity }); city.save(); //alert('Le modèle ' + myCity + ' a bien été créé car il n\'existait pas...'); } else{alert('Le modèle ' + myCity + ' n\'a pas été créé car il existe déjà');} } myCities.fetch({ success: function(coll) { alert("You have " + coll.length + " cities"); }, error: function() { alert("An error occurred"); } }); }, onerror: function(e) { // this function is called when an error occurs, including a timeout Ti.API.debug(e.error); alert('error'); }, timeout:5000 /* in milliseconds */ }); xhr.open("POST", url); xhr.send(); // request is actually sent with this statement $.index.open();Also, I create the collection each time the app starts and I don't know if this is a clean approach. Maybe should I check if the collection exists AND THEN create it in the case it doesn't, or instantiate it in the case it already has been created? In my loop, where a model is created, the model's name is also the same each time (var city), so is this a good way to do it or should I dynamically name each model?
Thanks for Help & advices!