Ember 路线如何?

Ember Routes How To?

我的问题是 "simple",但我无法用 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

的 link

路由必须开一个books/new模板,linknew book对象用他author:即我要显示<h1>New book from {{author.name}}</h1>

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

我看到了三种方法:

  1. 放在books资源下,要求作者作为路由参数:

    this.resource('books', function() {
        this.route('new', { path: '/new/:author_id' });
    });
    
  2. 将路由放在books资源下,但将作者放在query parameter下。

    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');
        }
    }
});