2013-08-05 82 views
0

這是我遇到的問題。Ember路由從一個嵌套對象轉換到另一個

假設你有兩個模型,Project和Post的應用程序。所有帖子都屬於特定項目。所以,帖子的路徑也包含項目ID(example.com/:project_id/:post_id)。

如何從項目A的帖子X過渡到項目B的帖子Y?只需從帖子B的路由中調用transitionToRoute('post',postA),就可以在帖子中保留帖子B的項目ID。

Here's a fiddle describing my predicament。正如你所看到的,當使用頁面頂部的項目鏈接時,正確的帖子出現在正確的項目中。但是,點擊「其他帖子」後面的鏈接,您將看到Ember如何在不正確的項目環境中顯示帖子。

如何在Ember中的這些「表親」路線之間轉換?

的JS:

window.App = Ember.Application.create({ 
    LOG_TRANSITIONS: true 
}); 

App.Store = DS.Store.extend({ 
    adapter: DS.FixtureAdapter 
}); 

App.store = App.Store.create(); 

App.Router.map(function(match) { 
    this.resource('projects'); 
    this.resource('project', {path: ':project_id'}, function(){ 
     this.resource('post', {path: ':post_id'}); 
    }); 
}); 

App.Project = DS.Model.extend({ 
    title: DS.attr('string'), 
    posts: DS.hasMany('App.Post') 
}); 

App.Post = DS.Model.extend({ 
    title: DS.attr('string'), 
    body: DS.attr('string'), 
    project: DS.belongsTo('App.Project') 
}); 

App.Project.FIXTURES = [ 
    { 
     id: 1, 
     title: 'project one title', 
     posts: [1] 
    }, 
    { 
     id: 2, 
     title: 'project two title', 
     posts: [2] 
    } 
]; 

App.Post.FIXTURES = [ 
    { 
    id: 1, 
    title: 'title', 
    body: 'body' 

    }, 
    { 
    id: 2, 
    title: 'title two', 
    body: 'body two' 
    } 
]; 

App.ApplicationController = Ember.ObjectController.extend({ 
    projects: function() { 
     return App.Project.find(); 
    }.property() 
}); 

App.PostController = Ember.ObjectController.extend({ 
    otherPost: function(){ 
     id = this.get('id'); 
     if (id == 1) { 
      return App.Post.find(2); 
     } else { 
      return App.Post.find(1); 
     } 
    }.property('id') 
}); 

而且模板:

<script type="text/x-handlebars" data-template-name="application"> 
    {{#each project in projects}} 
    <p>{{#linkTo project project}}{{project.title}}{{/linkTo}}</p> 
    {{/each}} 
    {{outlet}} 
</script> 

<script type="text/x-handlebars" data-template-name="project"> 
    <h2>{{title}}</h2> 
    {{#each post in posts}} 
     {{#linkTo post post}}{{post.title}}{{/linkTo}} 
    {{/each}} 
    {{outlet}} 
</script> 

<script type="text/x-handlebars" data-template-name="post"> 
    <h3>{{title}}</h3> 
    <p>{{body}}</p> 
    other post: {{#linkTo post otherPost}}{{otherPost.title}}{{/linkTo}} 
</script> 

回答

0

我發現3個問題。
1.您的belongsTo燈具數據缺少它們所屬的ID。

App.Post.FIXTURES = [ 
{ 
id: 1, 
title: 'title', 
body: 'body', 
project:1 
}, 
{ 
    id: 2, 
    title: 'title two', 
    body: 'body two', 
    project:2 
} 
]; 

2.當你過渡到一個資源,如果你只在一個單一的模式發送,它只會改變資源的模式,如果你想在路徑更新多個車型,發送所有所需車型

{{#linkTo 'post' otherPost.project otherPost}}{{otherPost.title} 

3 linkTo路線應加引號。 (將來也不會沒有他們正常工作),見上面

http://jsfiddle.net/3V6cy/1

BTW,感謝設立的jsfiddle,這讓我像一百萬次更容易回答的問題的例子。祝好運與燼,我們喜歡它!

+0

太棒了,非常感謝 - 我在嘗試{{#linkTo project.post項目發佈}}而不是{{#linkTo發佈項目帖子}}。後者工作正常。謝謝! – tobobo

相關問題