Javascript 在木偶mvc模式中,在何处放置不同的GETAPI调用
例如,我为我的用户实体设置了以下服务器路由:Javascript 在木偶mvc模式中,在何处放置不同的GETAPI调用,javascript,marionette,Javascript,Marionette,例如,我为我的用户实体设置了以下服务器路由: 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') .don
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);
});
});
App.addInitializer(function () {
App.user = new User();
App.user.fetchMe(); // performs the api call above
});
我的问题是这个API调用应该实际驻留在哪里。是否最好采用以下方式:
App.addInitializer(function () {
$.get('/users/me')
.done(function processCurrentUser (userJson) {
App.user = new User(userJson);
});
});
App.addInitializer(function () {
App.user = new User();
App.user.fetchMe(); // performs the api call above
});
或者我应该在控制器内部做些什么
谢谢你的帮助 在执行提取时,我总是担心它的asyn行为将如何影响依赖于该数据的组件。如果没有下游组件需要数据才能合理预期返回,那么您的方法在技术上没有问题 然而,还有另一种可能的方式来加载全局变量。我经常做的事情,对于用户列表也是如此,就是将数据引导到初始加载页面。我通常将其加载到窗口变量中。例如,在后端模板中
<script>
window.globals = {};
window.globals.currentUser = @Html.Raw(Json.Encode(ViewBag.User))
</script>
谢谢你的回复,我也考虑过这样做,也许最终会去做。为了避免您描述的问题,我最终使用了$.ajax并将async选项设置为false。在这个特定的应用程序中,我不需要数据,直到木偶应用程序开始,所以在我的情况下,这应该是好的,尽管引导可能解决了更普遍的问题。这种方法非常有效,而且它也是由主干框架实现的。