繁体   English   中英

灰烬路线如何?

[英]Ember Routes How To?

我的问题是“简单”,但是用Ember无法解决它。

这是一个小型图书馆应用程序,作者和书籍的路线正常

this.resource('books', function () {
    this.route('edit', {path: '/:book_id/edit'});
    this.route('show', {path: '/:book_id'});
});

this.resource('authors', function () {
    this.route('new');
    this.route('edit', {path: '/:author_id/edit'});
    this.route('show', {path: '/:author_id'});
});

现在,我想使用当前作者模板/authors/156的链接添加一条路线来注册新书

该路线必须打开books/new模板,并将new book对象与他的author链接:即,我要显示<h1>New book from {{author.name}}</h1>

我应该在现有路线上添加什么路线? 如何将作者引用传递给新书对象?

我看到了三种方法:

  1. 将其放在books资源下,并要求作者作为路径参数:

     this.resource('books', function() { this.route('new', { path: '/new/:author_id' }); }); 
  2. 将路线放在books资源下,但将作者放在查询参数中

     this.resource('books', function() { // Declare required query parameter on controller for `new` route this.route('new'); }); 
  3. 将路线置于authors下方,并在URL中要求作者:

     this.resource('authors', function() { this.route('new_book', { path: '/:author_id/new_book' }); }); 

我建议第三种选择,因为我认为这是最干净的。 在您的控制器中,您可以相当轻松地创建一本新书:

export default Ember.Controller.extend({
    actions: {
        createBook: function() {
            var author = this.get('model');
            var book = this.store.createRecord('book', {
                author: author,
                ...
            });

            book.save();
        }
    }
});

我已经尝试并成功了第二个建议的方法,查询参数。

路由器:

this.resource('books', function () {
    this.route('new');
    this.route('show', {path: '/:book_id'});
};

路线

App.BooksNewRoute = Ember.Route.extend({
    queryParams: {
        author_id: {
            refreshModel: true
        }
    },
    model: function (params) {
        var newBook = this.store.createRecord('book');
        this.store.find('author', params.author_id).then(function (author) {
            newBook.set('author', author);
        });
        return newBook;
    }
});

和控制器

App.BooksNewController = Ember.ObjectController.extend({
    queryParams: ['author_id'],
    author_id: null,
    actions: {
        save: function () {
            var controller = this;
            this.get('model').save().then(function (book) {
                controller.transitionToRoute('books.show', book);
            }, function (error) {
                console.error(error);
            });
        },
        cancel: function () {
            this.get('model').rollback();
            this.transitionToRoute('index');
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM