gpt4 book ai didi

javascript - 在 marionette mvc 模式中,在哪里放置不同的 get API 调用

转载 作者:行者123 更新时间:2023-11-28 07:21:16 25 4
gpt4 key购买 nike

例如,我为我的用户实体设置了以下服务器路由:

GET /users/      // gets collection of users
GET /users/:id // gets user :id
GET /users/me // gets the current user

在我的应用程序开始时,我想从服务器获取当前用户并将其存储......大致如下:

App.addInitializer(function () {
$.get('/users/me')
.done(function processCurrentUser (userJson) {
App.user = new User(userJson);
});
});

我的问题是这个 API 调用实际上应该驻留在哪里。最好有一些类似的东西:

App.addInitializer(function () {
App.user = new User();
App.user.fetchMe(); // performs the api call above
});

或者我应该在 Controller 内部做一些事情?

感谢您的帮助!

最佳答案

在进行获取时,我总是担心其 asyn 行为将如何影响依赖于该数据的组件。如果在合理预期数据返回之前没有下游组件需要数据,那么从技术上讲,您的方法没有任何问题。

但是,还有另一种可能的方式来加载全局变量。我经常做的事情(对于用户列表,也会发生这种情况)是将数据引导到初始加载页面。我通常将其加载到 window 变量上。因此,对于您的示例,在您的后端模板中,

<script>
window.globals = {};
window.globals.currentUser = @Html.Raw(Json.Encode(ViewBag.User))
</script>

当然,您可以将 @Html.Raw(Json.Encode(ViewBag.User)) (我们使用 C#)替换为您最喜欢的后端模型。

然后在您的应用程序启动时,您一定会拥有模型:

App.addInitializer(function () {
App.user = new User(window.globals.currentUser);
});

关于javascript - 在 marionette mvc 模式中,在哪里放置不同的 get API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30292075/

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