将集合而不是数组传递给fetch()。then()回调

时间:2015-12-29 14:10:55

标签: javascript backbone.js promise marionette deferred

从服务器获取数据并返回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);
    });

});


调用上述模块获取数据的模块

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


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


            });
});


如何将集合而不是数组作为then()中回调函数的参数,因为传递给回调的medicines参数在获取值后给出了数组。

2 个答案:

答案 0 :(得分:2)

将成功回调与选项一起传递,这些选项将作为骨干的第一个参数与集合一起调用:

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);

您可以使用:

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

答案 1 :(得分:1)

而不是直接返回xhr承诺,filter it via .then将您的集合设置为承诺值:

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

medicines中的第一个参数(MedicineManager.request(...).then(function (medicines) { });)将成为您的收藏。