5

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;
                          });
                    }                    
        }
 });
Stan Wiechers
  • 1,962
  • 27
  • 45

2 Answers2

13

A couple of solutions come 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 recommended, you could cause your request to become 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
            });
        }
    }
});
Michael Camden
  • 1,183
  • 8
  • 9
0

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 completion, 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 recommend doing some reading on callbacks (I've posted some resources below). Good luck!

javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

recurial.com/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.com/tutorials/wrangle-async-tasks-with-jquery-promises--net-24135

Duncan Smith
  • 359
  • 4
  • 6