Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Data Loading in Ractive.js

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;
                          });
                    }                    
        }
 });
like image 872
Stan Wiechers Avatar asked Apr 25 '14 20:04

Stan Wiechers


1 Answers

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
            });
        }
    }
});
like image 175
Michael Camden Avatar answered Sep 28 '22 10:09

Michael Camden