gpt4 book ai didi

javascript - 如何使用 Backbone.js 在 Bootstrap Modal 中加载 API 结果

转载 作者:行者123 更新时间:2023-11-30 12:40:09 24 4
gpt4 key购买 nike

我正在尝试在我使用 Backbone.js 构建的网络应用程序中打开一个 Bootstrap 模式。为此,我使用了这个 backbone.bootstrap-modal来自github。这在加载简单模式时很容易工作:

var ListUsersModalView = Backbone.View.extend({
render: function() {
this.$el.html($('#my-modal-template').html());
return this;
}
});

我使用这段代码展示:

new Backbone.BootstrapModal({
animate: true,
content: new ListUsersModalView()
}).open();

我现在尝试从 API 调用中将模型列表加载到模型中。我现在有以下代码:

var ListSupportersModalView = Backbone.View.extend({
el: '#div-for-list-of-names',
render: function() {
var that = this;
var users = new UserCollection();
users.fetch({
success: function() {
var template = _.template($('#my-modal-template').html(), {users: users.models});
that.$el.html(template);
return that;
}
});
}
return that;
});

这行不通,我明白为什么;我需要返回 this 包括加载的集合。不幸的是,用户是异步获取的,因此最后一个 return that; 不包括用户模型。

现在的问题是;我该如何解决这个问题?如何将模型从 API 调用加载到模态中?欢迎所有提示!

最佳答案

在我看来,Jquery 的延迟对象是解决这个问题的最佳方式。

这可以让您返回一个稍后将在您的代码中处理的“ promise ”。一旦您解决或拒绝 promise ,您就可以处理显示数据或在拒绝时显示错误。 (更多信息可以在这里阅读 http://api.jquery.com/category/deferred-object/ )

关于如何重组以利用它的快速示例

var ListSupportersModalView = Backbone.View.extend({
users: null,

// This tells the view which element is its container
// remove this if you don't need it.
el: '#div',

initialize: function() {
this.users = new UserCollection();
},

//moved this to a it's own function so that it can
//return the promise for action it is completing
getUsers: function() {
var defer = $.Deferred();
this.users.fetch({
success: function() {
//users should now be a full collection so
//resolve the promise
defer.resolve();
},
error: function() {
//users fetch failed so reject the promise
defer.reject();
}
});

//return the promise from the deferred object
var promise = defer.promise();
return promise;


},
render: function() {

var template = _.template($('#my-modal-template').html(), {
users: this.users.models
});
this.$el.html(template);

return this;
}

});

然后在设置 Bootstrap 模式时

var listUsersModalView = new ListUsersModalView();

//get the users and this will return the prmoise;
var listUsersModalViewPromise = listUsersModalView.getUsers();


//set up listen for when the promise is resolved/rejected
$.when(listUsersModalViewPromise).done(function() {


//only change i have made is to pass the listUserModalView that has already
//been initialized as this will now have a fetched user collection
new Backbone.BootstrapModal({
animate: true,
content: listUsersModalView
}).open();
}).fail(function() {
//do something here to show that an error occured?
});

关于javascript - 如何使用 Backbone.js 在 Bootstrap Modal 中加载 API 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24776814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com