Ember Routes如何?

时间:2015-04-06 21:37:43

标签: ember.js ember-data

我的问题是“简单”,但我无法用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>

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

2 个答案:

答案 0 :(得分:0)

我看到了三种方法:

  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下,并在网址中要求作者:

    this.resource('authors', function() {
        this.route('new_book', { path: '/:author_id/new_book' });
    });
    
  4. 我建议第三种选择,因为我认为这是最干净的选择。在您的控制器中,您可以非常轻松地创建新书:

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

答案 1 :(得分:0)

我已尝试并使用第二种建议的方法取得成功,查询参数。

路由器:

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