使用jquery deferred.resolve方法的常用方法是在你有一个回调函数时调用它,它给你一个完全加载的响应,因为在这种情况下xhr在加载时添加一个事件监听器并提供对deferred.resolve的xhr响应。
从以下示例之一复制以下代码。 http://www.danieldemmel.me/blog/2013/03/22/an-introduction-to-jquery-deferred-slash-promise/
function getData(){
var deferred = $.Deferred();
XMLHttpRequest xhr = new XMLHttpRequest();
xhr.open("GET","data",true);
xhr.addEventListener('load',function(){
if(xhr.status === 200){
deferred.resolve(xhr.response);
}else{
deferred.reject("HTTP error: " + xhr.status);
}
},false)
xhr.send();
return deferred.promise();
}
我当前使用Marionette请求 - 响应处理程序检索数据的代码。无论如何我可以从以下请求获得回调响应
function getData(activityID) {
var defer = $.Deferred();
require(["entities/element/element_collection"], function() {
var fetchData = App.request("element:entities:initialize", activityID);
//Example code scenario
// How do i know my request is being fulfilled? and used Deferred.resolve accordingly.
//maybe something as follows?
fetchData.success(function(response){
defer.resolve(response);
});
//Example code scenario
});
return defer.promise();
};
请求处理程序基本上将返回一个Backbone集合,该集合将通过将一组对象传递到新的Backbone集合中生成。
答案 0 :(得分:0)
如果(因为它会显示)require()
是异步的并且App.request()
是同步的,那么您可以按如下方式编写代码:
function getData(activityID) {
var defer = $.Deferred();
require(["entities/element/element_collection"], function() {
var fetchData = App.request("element:entities:initialize", activityID);
defer.resolve(fetchData);
});
return defer.promise();
};
getData(activityID).done(function(fetchData) {
//do awesome stuff with fetchData here
});
或者,取决于您希望在getData()
中执行的次数/次数,具体如下:
function getData() {
var defer = $.Deferred();
require(["entities/element/element_collection"], defer.resolve);
return defer.promise();
};
getData().done(function() {
var fetchData = App.request("element:entities:initialize", activityID);
//do awesome stuff with fetchData here
});
但是,如果App.request()
也是异步的,那么它就无法返回数据 - 它必须返回数据的承诺,代码将是这样的:
function getData(activityID) {
var defer = $.Deferred();
require(["entities/element/element_collection"], function() {
App.request("element:entities:initialize", activityID).done(defer.resolve);
});
return defer.promise();
};
getData(activityID).done(function(fetchData) {
//do awesome stuff with fetchData here
});
或:
function getData() {
var defer = $.Deferred();
require(["entities/element/element_collection"], defer.resolve);
return defer.promise();
};
getData().done(function() {
App.request("element:entities:initialize", activityID).done(function(fetchData) {
//do awesome stuff with fetchData here
});
});
如果App.request()
是异步的,既不返回承诺也不接受回调,那么编写它的人需要与之通话。 App.request()
需要重写,否则您需要找到另一个实用工具来完成这项工作。
答案 1 :(得分:0)
从服务器获取数据默认情况下是异步调用,那么为什么不使用命令而不是请求/响应并监听模型事件?我认为这会更容易。 在这个主题上,我将创建一个提供的频道,
然后控制器只需订阅通道来获取数据,并将监听集合实例事件(同步错误更改,无论您想要的模型/集合上的基本骨干事件)
/* Constants: Simulation of API data. */
Constants = {};
Constants.jsonLanguages = [
{Name: "English", Code: "en", isEditable:true},
{Name: "French", Code: "fr", isEditable:false},
{Name: "German", Code: "de", isEditable:true},
{Name: "Spanish", Code: "es", isEditable:false}
];
Constants.jsonBook = {
Title: "Dune",
AuthorName: "Frank Herbert",
LanguageCode: "en",
ISBN: "978-1-4493-9268-0"
};
/* ----------------------------------------------------------------------------- */
/* Models */
// Language/Models.js
var models = {};
models.Language = Backbone.Model.extend({
defaults: {
Name: "English",
Code: "en"
},
idAttribute:"Code",
url: "/echo/json/"
});
models.LanguageCollection = Backbone.Collection.extend({
model: models.Language,
url: "/echo/json/"
});
// Book/Models.js
models.Book = Backbone.Model.extend({
defaults: {
Title: "",
AuthorName: "",
Language: null
},
url: "/echo/json/",
idAttribute: "ISBN"
});
/* ----------------------------------------------------------------------------- */
/* Channels: Manage data between server and client.
- dependencies : wreqr, related models, related routes */
// Languages/Channel.js
var LanguageChannel = {};
LanguageChannel.data = {};
LanguageChannel.data.workingLanguage = new models.Language();
LanguageChannel.data.languages = new models.LanguageCollection();
LanguageChannel.channel = Backbone.Wreqr.radio.channel("Languages");
LanguageChannel.channel.commands.setHandler("getLanguages", function() {
// here you typically fetch the data using backbone collection and backbone router
window.console && console.log("LanguageChannel.channel.command.getLanguages()");
LanguageChannel.data.languages.reset(Constants.jsonLanguages);
LanguageChannel.data.languages.trigger("sync");
});
// Books/Channel.js
var BookChannel = {};
BookChannel.data = {};
BookChannel.data.book = new models.Book();
BookChannel.channel = Backbone.Wreqr.radio.channel("Books");
BookChannel.channel.commands.setHandler("getBook", function(id){
// here you typically fetch the data using backbone model & backbone router
window.console && console.log("BookChannel.channel.commands.getBook(" + id +")");
BookChannel.data.book.set(Constants.jsonBook, {reset:true});
BookChannel.data.book.trigger("sync");
});
/* ----------------------------------------------------------------------------- */
/* Views: Manage template and view events. */
// Book/Views.js
BookAttributesView = Marionette.ItemView.extend({
el: "#BookAttributesBox",
template: "#BookAttributesTemplate",
bindings:
{
"#Title": "Title",
"#AuthorName": "AuthorName",
"#LanguageCode": {
observe: "LanguageCode",
selectOptions: {
collection: LanguageChannel.data.languages,
labelPath: "Name",
valuePath: "Code"
},
update: function($el, val, model, options) {
window.console && console.log("View.bindings.#LanguagageCode:update");
LanguageChannel.data.languages.each(function(language){
// Find parent.
var parent = $el.find("#LanguageReadable");
if (language.get("isEditable")){
parent = $el.find("#LanguageEditable");
}
// Select correct value.
var selected = "";
if (language.get("Code") == val){
selected = ' selected="selected"';
}
// Add option to optgroup.
parent.append("<option" + selected + ">" + language.get("Name") + "</option>");
});
}
}
},
onRender: function () {
window.console && console.log("View.onRender");
this.stickit();
}
});
/* ----------------------------------------------------------------------------- */
/* Controllers: Manage page behaviour. */
// Books/Controller.js:
BookController = Marionette.Controller.extend({
initialize: function(){
window.console && console.log("Controller.ctor");
var self = this;
self.bookId = "978-1-4493-9268-0"
// Callbacks from data channels.
self.listenTo(LanguageChannel.data.languages, "sync", self.onSyncLanguages);
self.listenTo(BookChannel.data.book, "sync", self.onSyncBook);
// Retrieve data.
LanguageChannel.channel.commands.execute("getLanguages");
BookChannel.channel.commands.execute("getBook", self.bookId);
},
/* Book functions */
onSyncBook: function(){
window.console && console.log("Controller.onSyncBook");
this.showBookAttributes(); // TODO, use : LanguageChannel.data.languages.fetch();
},
showBookAttributes: function(){
window.console && console.log("Controller.showBookAttributes");
new BookAttributesView({ model: BookChannel.data.book }).render();
},
/* Language functions */
onSyncLanguages: function(){
window.console && console.log("Controller.onSyncLanguages")
this.showBookAttributes();
}
});
/* ----------------------------------------------------------------------------- */
/* Aplication.js: Starts the backbone application (main entry point). */
// Book/Application.js
Application = Marionette.Application.extend({
onStart: function(){
window.console && console.log("Application.start()");
new BookController();
}
});
fiddle link展示如何做 - 当然,在你的项目中,你需要“要求你的几个模块”。
小提琴链接基于C0b0ll -actually,一位同事 - 在stickit usage-yes another jsFiddle link上做了
这样做,控制台将记录下来: