Flake
Flake

Reputation: 1406

pass a collection instead of array to fetch().then() callback

Module which fetches data from the server and returns a Promise

MedicineManager.module("Entities", function (Entities, MedicineManager, Backbone, Marionette, $, _) {
    Entities.Suggestion = Backbone.Model.extend({
        default: {
            suggestion: ""
        }
    });

    Entities.SuggestionCollection = Backbone.Collection.extend({
        model: Entities.Suggestion,
        comparator: "suggestion"
    });

    var API = {
        getSuggestions: function (medicine) {
            var suggestions = new Entities.SuggestionCollection();
            suggestions.url="/medicine_suggestions/?id=" + medicine;
            return suggestions.fetch();
        }
    };

    MedicineManager.reqres.setHandler("suggestion:entities", function (medicine) {
        return API.getSuggestions(medicine);
    });

});


Module which calls the above module for getting fetched data

MedicineManager.module("MedicinesApp.Suggest", function (Suggest, MedicineManager,
    Backbone, Marionette, $, _) {


            MedicineManager.request("suggestion:entities", "paracetamol").then(function (medicines) {


            });
});


How do I get collection instead of an array as the parameter to the callback function in then() because the medicines parameter passed to the callback is giving an array after fetching the values.

Upvotes: 3

Views: 106

Answers (2)

nikoshr
nikoshr

Reputation: 33344

Instead of directly returning the xhr promise, filter it via .then to set your collection as the promised value :

var API = {
    getSuggestions: function (medicine) {
        var suggestions = new Entities.SuggestionCollection();
        suggestions.url="/medicine_suggestions/?id=" + medicine;
        return suggestions.fetch().then(function() {
            return suggestions;
        });
    }
};

The first argument (medicines) in MedicineManager.request(...).then(function (medicines) { }); will be your collection.

Upvotes: 1

T J
T J

Reputation: 43156

Pass the success callback along with options, which will be invoked with the collection as first argument by backbone:

Entities.SuggestionCollection = Backbone.Collection.extend({
  model: Entities.Suggestion,
  comparator: "suggestion"
});

var API = {
  getSuggestions: function(medicine, options) {
    var suggestions = new Entities.SuggestionCollection([],{
      url : "/medicine_suggestions/?id=" + medicine
    });
    return suggestions.fetch(options);
  }
};
 MedicineManager.reqrest.setHandler("suggestion:entities",API.getSuggestions);

Which you can use like:

MedicineManager.request("suggestion:entities", "paracetamol", {
  success: function(medicines) {}
});

Upvotes: 2

Related Questions