I like to pull in some remote data when rendering a ractive template. Due to the async nature of the request no data makes it into output. How can I make that happen?
var ractive = new Ractive({
debug: true,
el: 'container',
template: '#template',
data:
{
chapters:chapters,
load_text: function(path)
{
$.get(path, function( text ) {
return text;
});
}
}
});
I like to pull in some remote data when rendering a ractive template. Due to the async nature of the request no data makes it into output. How can I make that happen?
var ractive = new Ractive({
debug: true,
el: 'container',
template: '#template',
data:
{
chapters:chapters,
load_text: function(path)
{
$.get(path, function( text ) {
return text;
});
}
}
});
Share
Improve this question
edited Apr 25, 2014 at 21:15
Stan Wiechers
asked Apr 25, 2014 at 20:07
Stan WiechersStan Wiechers
2,09232 silver badges48 bronze badges
2 Answers
Reset to default 13A couple of solutions e to mind;
Create the Ractive object, make the request, and then call 'set' on the ractive object when you have data.
var ractive = new Ractive({
debug: true,
el: 'container',
template: '#template',
data: {
chapters: chapters,
load_text: ''
}
});
$.get(path, function( text ) {
ractive.set('load_text', text);
});
Alternatively, and this is not remended, you could cause your request to bee synchronous.
var ractive = new Ractive({
debug: true,
el: 'container',
template: '#template',
data: {
chapters: chapters,
load_text: function(path) {
$.ajax({
url: path,
success : function (text) {
return text;
},
async : false
});
}
}
});
The reason that your call to $.get
isn't returning any values, is because the function that you pass it is a callback (a function passed as a parameter to another function, to be executed upon the first function's pletion, without blocking).
The actual $.get
function returns nothing. The reason you pass it a callback is so that, when it's done running, it can call that callback (with the result of $.get
as a parameter). Also, unless you're calling ractive.data.load_text()
somewhere in your application the function that you've assigned to load_text
will never run.
What worries me is that the code you posted demonstrates a fundamental lack of understanding of how Javascript (and in particular, asynchronous operations in Javascript) work. I remend doing some reading on callbacks (I've posted some resources below). Good luck!
javascriptissexy./understand-javascript-callback-functions-and-use-them/
recurial./programming/understanding-callback-functions-in-javascript/
Also, when you're ready to graduate from callbacks, here's an article on promises in jQuery: http://code.tutsplus./tutorials/wrangle-async-tasks-with-jquery-promises--net-24135