gpt4 book ai didi

ember.js - 想调用 setupController 或模型钩子(Hook)

转载 作者:行者123 更新时间:2023-12-02 06:04:22 25 4
gpt4 key购买 nike

我有以下路线和 Controller :

var App = App || Ember.Application.create();

App.Router.map(function(){
this.resource('posts', function(){
this.route('new', { path: '/new'});
});
});

App.PostsRoute = Ember.Route.extend({
model: function () {
return $.getJSON('/api/posts');
},
setupController: function(controller, model) {
$.getJSON('/api/posts').done(function(data) {
controller.set('model', data);
});
});

App.PostsNewController = Ember.Controller.extend({
actions: {
addPost: function (file) {
var self = this;
$.ajax({
type: 'POST',
url: '/api/posts',
data : {
id: this.get('id'),
title: this.get('title'),
author: this.get('author'),
contents: this.get('contents')
}
}).done(function(res){
self.transitionToRoute('posts');
});
}
}
});

我想要做的是在用户成功保存新帖子后调用“帖子”路由以刷新浏览器中的帖子列表。

所以我使用“self.transitionToRoute('posts')”在 PostsRou​​te 中调用模型钩子(Hook)或 setupController,但这两种方法都没有被调用。

我究竟做错了什么?
提前致谢。

最佳答案

由于您已经在帖子路线上,Ember 认为没有必要重新获取模型。此外, Controller 已经设置好,并且已经有了模型,所以它也没有理由调用它。从本质上讲,它是在避免浪费电话。我个人建议避免添加回调(除非您期待其他用户的其他帖子)。

示例 1:只需将新帖子添加到当前帖子列表中

needs: ['posts'],
actions:{
addPost: function (file) {
var self = this,
data = {
id: this.get('id'),
title: this.get('title'),
author: this.get('author'),
contents: this.get('contents')
};
$.ajax({
type: 'POST',
url: '/api/posts',
data : data
}).done(function(res){
// just push the new data
self.get('controllers.posts').pushObject(data);
self.transitionToRoute('posts');
});
}
}

示例 2:通过发送一个 Action 再次获取所有帖子,该 Action 将冒泡到帖子路由
actions:{
addPost: function (file) {
var self = this,
data = {
id: this.get('id'),
title: this.get('title'),
author: this.get('author'),
contents: this.get('contents')
};
$.ajax({
type: 'POST',
url: '/api/posts',
data : data
}).done(function(res){
self.send('updatePosts');
self.transitionToRoute('posts');
});
}
}

App.PostsRoute = Ember.Route.extend({
model: function () {
return $.getJSON('/api/posts');
},
actions: {
updatePosts: function(){
var controller = this.get('controller');
this.model().then(function(data){
controller.set('model', data);
});
}
}
});

关于ember.js - 想调用 setupController 或模型钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21659735/

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