0

Using vktemplate isn't quite working when I try to use jquery deferreds. Since the vktemplate makes an ajax call of its own, the deferred gets resolved before vktemplate completes its work, and its optional callback. How can I set up vk so that the promise doesn't get resolved until after these two things happen?

$(document).on('click', '.ajax', function() {
    $.when(ajax1('<p>first</p>'), 
           ajax2('<p>second</p>'), 
           ajax3('<p>third</p>'))
     .then(function(results1, results2, results3) {
        console.log(results1);
        $('.document').append(results1);
        $('.document').append(results2); 
        $('.document').append(results3);         
        alert('all ajax done');
    });
});

function ajax1(data) {

    $.ajax({
        type: 'post',
        url: 'templates/test_template.tmpl',
        data: "data=" + data,
        dataType: 'json',
        success: function (returnedData) {

            $('#resultsDiv').vkTemplate('templates/test_template.tmpl', returnedData, function () {
                //vk callback
                //possibly call my resolve here?
            });
        }
    });
}

function ajax2(data){//more of the same}
1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

1

Since vkTemplate returns nothing you need to manually create a deferred and resolve it in success callback with required data.

function ajax1(data) {
    var dfd = $.Deferred();

    $.ajax({
        type: 'post',
        url: 'templates/test_template.tmpl',
        data: "data=" + data,
        dataType: 'json',
        success: function (returnedData) {

            $('#resultsDiv').vkTemplate('templates/test_template.tmpl', returnedData, function (el, data, context) {
                dfd.resolveWith(context, [$(el)]);
            });
        }
    });

    return dfd.promise();
}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Resolves a deferred with context and arguments. http://api.jquery.com/deferred.resolveWith/ – Yury Tarabanko Nov 19 '12 at 22:21
  • Actually, where do these arguments in the callback come from? `(el, data, context)` are they a part of vktemplate or do they come from deferred object? – 1252748 Nov 20 '12 at 17:19
  • It's interesting because my `success` callback uses the parameter `returnedData`, but both `returnedData` and `data` show the same object when I print them to the console. Do you know why that is? Thanks! – 1252748 Nov 20 '12 at 17:24
  • vkTemplate passes data it was called with `if(callback) {callback(elm, jsonObj, context);}` – Yury Tarabanko Nov 20 '12 at 20:27