从服务器获取数据并返回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
参数在获取值后给出了数组。
答案 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) { });
)将成为您的收藏。