2015-04-06 51 views
0

我的问题是“简单”,但我不能与Ember解决这个问题....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模板,并与他author链接new book对象:即我想显示<h1>New book from {{author.name}}</h1>

我应该添加哪些路线到现有路线? 如何将作者参考传递给新书对象?

回答

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下,需要笔者在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(); 
     } 
    } 
}); 
+0

首先,感谢这个答案。也许我错了,但我不喜欢创建'author.newbook route'的想法。我更喜欢'book.new'。我正在尝试第一个选项'book/new /:author_id',但是现在我又陷入了另一个问题:如何将新书链接到作者。我认为它必须在'BookNewRoute'内完成,'model:function(){return this.store.createRecord('book')}'但是怎么做? –

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