Search code examples
backbone.jsunderscore.jsmarionettedata-synchronization

Make templateHelpers wait until async function ends in Marionette


I'm using the Storage plugin of phonegap in a Marionette ItemView, but could be any asynchronous stuff. I just want to pass a variable throw the template helper, which has to wait until (in this case) DB operations end.

I also tryed putting the asynchronous piece of code inside the templateHelpers function, but it does not wait, and the value variable is empty in the template.

initialize: function(options){
    that=this;
    var db = window.openDatabase("MyDB", "1.0", "My Database", 200000);
    db.transaction(queryDB, errorCB);

    function queryDB(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS MyDB (id unique, name, value)');
        var query = "SELECT * FROM MyDB WHERE id="+that.model.get('id')+" LIMIT 1";
        tx.executeSql(query, [], querySuccess, errorCB);
    }

    function errorCB(err) {
        alert("Error processing SQL: "+err.code);
    }

    function querySuccess(tx, results) {
        var len = results.rows.length;
        if(len>0)
            that.value = results.rows.item(0).value;
    }                             

},

templateHelpers: function(){
    var helperParams = {};
    var val = {"value": this.value };
    _.extend(helperParams, val);
    return helperParams;
},

Any ideas?


Solution

  • As discussed in the comments, the solution is to re-render the view after your async load completes. This works because the render method in your Marionette view will call templateHelpers again and specifically will not call initialize again.

    function querySuccess(tx, results) {
        var len = results.rows.length;
        if(len>0)
            that.value = results.rows.item(0).value;
        that.render(); // <<< Re-render on success
    }