Warz Warz - 5 months ago 17
Javascript Question

making ajax request in meteor helpers

How can i wait until the ajax request finishes when returning data to a meteor helpers method.

For example,

Template.item.helpers({

itemName:function () {
var user = Meteor.user();

$.when(reallyLongAjaxRequest()).done(function (a1) {
//tried using jquery when
return "Item Name should have this because it waited";
});

return " Doesnt wait at all";
}
});


I have a
reallyLongAjaxRequest()
running and i would like it to finish before continuing on with my itemName helper. The log statement to console always shows undefined but that's because the ajax request hasn't finished. I tried using the jquery when with no luck. Any ideas

Edit:

I should mention that i am inside the helper function for a reason. I need the item 'id' being rendered so that i can run the ajax request with that paramater. Using reactive sessions would be perfect but i don't know of a way to get currently rendering items outside of the helpers method definition?

Answer

An unnamed collection is one where null is passed for the name. It is an in-memory data structure, not saved to the database. (http://docs.meteor.com/#meteor_collection)

OK, given a Meteor collection called "items" and wanting to do an ajax request for each item based on the item _id, and then being able to reference the ajax result in a template, this is what I'd do:

(roughly)

var Items = new Meteor.Collection('items');
var Results = new Meteor.Collection(null);

Items.find().observeChanges({
  added: function (id) {
    $.get(url, {id: id}, function (data) {
      if (Results.findOne(id))
        Results.update(id, {$set: {result: data}});
      else
        Results.insert({_id: id, result: data});
    });
  }
});

Template.item.itemName = function (id) {
  var doc = Results.findOne(id);
  if (doc)
    return doc.result;
  else
    return "";
};

inside your html you'll need to pass in the id to the helper:

{{itemName _id}}

Is there no way to just timeout for a few seconds when defining the helper so that my ajax request finishes without immediately returning.

No, with reactive programming things happen immediately, but you update when you have new stuff.