I started to work with a mobile framework LungoJS. Me and javascript not work quite fine but really i want modify this original code:
ORIGINAL.JS
var mock = function() {
var mock = [];
for (var i=1; i<=5; i++){
mock.push({
id: i,
name: 'name n'+i,
description: 'description n'+i
})
}
lng.View.Template.List.create({
container_id: 'lives',
template_id: 'show_music_template',
data: mock
})
}
return {
mock: mock
}
})(LUNGO, App);
This original code works fine and it’s easy, now I want do request using $.get who returns a JSON file and fill array like the ORIGINAL.JS:
JSON RESULT:
{"result":[
{"id":"52","username":"jgali","image":"Prova_(live)387.jpeg","name":"Prova (live)","type":"music","language":"Catalan","category":"8","tags":"indie, dine prova, indie live","description":"Aquesta es una prova online de reidiou","licence":"Reidiou License","played":"54","record_time":"45","facebook_id":"1052266203_2342869925158","twitter_hash":"#Provalive","create_date":"2011-11-01 13:04:21"},
{"id":"52","username":"jgali","image":"Prova_(live)387.jpeg","name":"Prova (live)","type":"music","language":"Catalan","category":"8","tags":"indie, dine prova, indie live","description":"Aquesta es una prova online de reidiou","licence":"Reidiou License","played":"54","record_time":"45","facebook_id":"1052266203_2342869925158","twitter_hash":"#Provalive","create_date":"2011-11-01 13:04:21"}
]}
SERVICE.JS
var mock = function() {
var mock = [];
var url = 'http://localhost/app/rest/podcasts';
var data = {};
//lng.Service.get = $get
lng.Service.get(url, data,function(response) {
var array = [];
//Do something with response
jQuery.each(response.result, function() {
mock.push({
id: this.id,
name: this.name,
description: this.description
})
});
document.write(mock[1].id);
});
lng.View.Template.List.create({
container_id: 'lives',
template_id: 'show_music_template',
data: mock
})
}
return {
mock: mock
}
The problem is outside loop i can’t use “mock” array. Sure I make a several mistake…but anybody knows what is the problem?
Thanks.
The problem is that
$.get()needs time to execute, and is therefore asynchronous. Asynchronous calls like this involve the use of acallbackfunction. To get access to themockarray you need to nest anything within this callback.You can also force AJAX calls to be synchronous in jQuery (though I, and the docs, warn against this); according to the docs: