如何在相应路线外设置“新建”和“保存”按钮

How to have New and Save buttons outside the corresponding route

本文关键字:新建 按钮 保存 设置 外设 应路      更新时间:2023-09-26

我有一个很容易用图片解释的挑战:应用程序控制器和文章的说明控制器

我想要的是,当我点击save时,在App.ArticlesNewController中调用saveArticle操作。

模板

<div class="buttonBlock">
    {{#linkTo "articles.new" class="newButton"}}Nieuw{{/linkTo}}
    {{#linkTo action="saveArticle" class="newButton storeButton"}}Opslaan{{/linkTo}} // generates an error: "This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid. "
</div>

路线

App.Router.map(function () {
    this.resource('articles', {path: "/articles"}, function() {
        this.resource('article', {path: '/:article_id'}); // works fine
        this.route('new', {path: "/new"}); // displays also without errors
    });
});

控制器

App.ApplicationController = Ember.ObjectController.extend({
    actions: {
        // got never called
        saveArticle: function () {
            console.log('ApplicationRoute saveArticle action');
            this.controllerFor('articles.new').send('saveArticle')
        }
    }
});

路线

App.ArticlesNewRoute = Ember.Route.extend({
    renderTemplate: function () {
        console.log('ArticlesNewRoute try to render article with controller articles.new');
        this.render('article', {
            controller: 'articles.new'
        });
    },
    model: function () {
        console.log('ArticlesNewRoute returning model');
        return this.store.createRecord('article');
    },
    actions: {
        // this will never be called
        saveArticle: function () { 
            console.log('ArticlesNewRoute saveArticle action');
            this.currentModel.save();
        }
    }
});

请注意,目前我在App.ArticlesNewRoute中有一篇新文章的操作,这显然不适用于this.controllerFor('articles.new').send('saveArticle')调用。

saveArticle操作的真正问题是,它也从不在App.ApplicationController中调用。

我还在模板中使用了{{controller}}。我确信模板中的按钮是由App.ApplicationController处理的,但调用从未被触发。

有什么想法吗?

您的代码中很少有问题

1) link-to仅用于路由。在你的情况下,我建议如下。

<a class="newButton storeButton" {{action "saveArticle"}}>Opslaan</a>

2) 您不应该在控制器中使用this.controllerFor()。据我记忆所及,它已被弃用。它目前仅在路线中可用。您应该使用needs并尝试从中访问控制器。有关needs的更多信息,请访问链接。

http://darthdeus.github.io/blog/2013/01/27/controllers-needs-explained/