Alloy MVC Framework Titanium Network (Model)
- by flyingDuck
I'm trying to authenticate using the Model in Alloy. I have been trying to figure this problem out since yesterday. If anybody could help me, I'd really appreciate it.
So, I have a view login.xml, then a controller login.js. The login.js contains the following function:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
if(user.login($.username.value, $.password.value)){
Alloy.createController('home').getView().open();
$.login.close();
}
}else{
alert('Username and/or Password required!');
}
}
Then in my user.js model, it's like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
alert(_this.get('email')); //alert email
},
});
When I click on login in login.xml it calls the function login in index.js. So, now my problem is that, when I click the button for the first time, I get an empty alert from alert(_this.get('email')), but then when I click the button the second time, everything works fine, it alerts the email. I have no idea what's going on. Thank you for the help.