emberjs中的嵌套对象

时间:2013-07-10 21:27:40

标签: ember.js

我有一个小的余烬集加载产品并显示它们。因此,每个产品都有商店知道我想从产品页面链接到商店,但我不知道我必须告诉ember产品有商店

window.App = Ember.Application.create()

App.Router.map ->
  @route 'products'
  @route 'product', path: '/product/:product_id'
  @route 'store', path: '/store/:store_id'

App.ProductsRoute = Ember.Route.extend

  setupController: (controller)->
    $.get('api', (response) ->
      products = response.response.products //this object holds the store
        .filter((p)->  p.gender == 'male')
        .map ((p)-> App.Product.create(p))

      controller.set('content', products)
    )
    controller.set 'name', 'Produkte'


App.Product = Ember.Object.extend
  style: (->
    "background-image:url('" + @get("image") + "')"
  ).property("url")

模板

script(type="text/x-handlebars", data-template-name="product")
    <h1>{{page_title}}</h1>
    <img {{bindAttr src="image"}}>
    {{#linkTo "store" store}}Store{{/linkTo}}

产品json

[
  {
    id: 1
    name: 'product1',
    gender: 'male'
    store: {id: 1, name: 'store1'}
  }
]

2 个答案:

答案 0 :(得分:0)

好像你有应该工作

我制作了一个简单的JSBIN来模拟你的api并且有一个有效的store link

App = Ember.Application.create();
App.Router.map(function() {
  this.route("store", {path: 'store/:store_id'});
});

App.IndexRoute = Ember.Route.extend({
  model: function(){
      return [{ id: 1, name: 'product1', gender: 'male', store: {id: 1, name: 'store1'}}];
  }
});

<script type="text/x-handlebars">{{outlet}}</script>
<script type="text/x-handlebars" id="index">
  <h2>All Products:</h2>
  <ul>
    {{#each}}
      <li>{{name}} - {{#linkTo "store" store}}Store{{/linkTo}}</li>
    {{/each}}
  </ul>
</script>
<script type="text/x-handlebars" id="store">
  <h1>Store: {{name}}</h1>
</script>

答案 1 :(得分:0)

好吧,这似乎是余烬WTF时刻之一。 store变量似乎是某种保留字。当我将密钥设置为_store时,它按预期工作:

window.App = Ember.Application.create()

App.Router.map ->
  @route 'products'
  @route 'product', path: '/product/:product_id'
  @route 'store', path: '/store/:store_id'

App.ProductsRoute = Ember.Route.extend

  setupController: (controller)->
    $.get('api', (response) ->
      products = response.response.products
        .filter((p)->  p.gender == 'male')
        .map ((p)->
          p._store = p.store
          App.Product.create(p))

      controller.set('content', products)
    )
    controller.set 'name', 'Produkte'

App.ProductRoute = Ember.Route.extend
  setupController: (controller, model)->
    console.log(model);

App.Product = Ember.Object.extend
  style: (->
    "background-image:url('" + @get("image") + "')"
  ).property("url")