【问题标题】:Displaying a model associated with a separate controller显示与单独控制器关联的模型
【发布时间】:2013-06-21 11:42:15
【问题描述】:

我有一个模型 WebsiteTemplate 属于 WebLayout。在 UI 中,我想显示所有 webLayouts 的列表,但能够将 html 类添加到 id 与 webLayout 相同的类中。 webLayout 属于websiteTemplate,这是我们正在访问的路线的模型。

关于如何做到这一点的任何想法?我知道我的设置也可能存在根本性错误,因此欢迎对此提出想法。似乎我想用特定的webLayout 将另一个参数传递给render,但这似乎不是Ember 的方式。

# website_template model
App.WebsiteTemplate = DS.Model.extend
 webLayout: DS.belongsTo("App.WebLayout")

# website_layout model
App.WebLayout = DS.Model.extend
 name: DS.attr("string"),
 thumbnail: DS.attr("string")

# router
App.Router.map ->
 @resource "website_template", path: "/website_template/:website_template_id"

# website_template route
App.WebsiteTemplateRoute = Ember.Route.extend
 setupController: ->
 @controller.set 'webLayouts',  App.WebLayout.find()

# website_template template
{{webLayout.id}}
{{render "_webLayouts" webLayouts}}

# web_layouts template
<ul>
 {{#each controller}}
  <li>
   <a href="#" {{ action "addLayout" this }}>
    <img alt="Thumbnail" {{ bindAttr src="thumbnail" }}>
    {{ name }}
   </a>
  </li>
 {{/each}}
</ul>

我知道以下行不通,但这是我正在尝试实现的想法的伪代码。

# website_template template
{{render "_webLayouts" webLayouts webLayout}}

# web_layouts template
<ul>
 {{#each webLayouts in controller}}
   {{#if webLayouts.id is webLayout.id}}
    <li class="selected">
   {{else}}
    <li>
   {{/end}}
    <a href="#" {{ action "addLayout" this }}>
    <img alt="Thumbnail" {{ bindAttr src="thumbnail" }}>
    {{ name }}
   </a>
  </li>
 {{/each}}
</ul>

【问题讨论】:

  • 你能显示你的WebLayout模型的定义吗?
  • @intuitivepixel 我用WebLayout 模型编辑了这个问题。目前没有关联。
  • 当你使用belongsTo 声明两个模型之间的一对一关系时,我猜应该有和关联...

标签: javascript ember.js coffeescript ember-data


【解决方案1】:

乍一看,我所缺少的是正确设置两个模型之间的一对一关系。

例子:

# website_template model
App.WebsiteTemplate = DS.Model.extend
  webLayout: DS.belongsTo("App.WebLayout")

# website_layout model
App.WebLayout = DS.Model.extend
  name: DS.attr("string"),
  thumbnail: DS.attr("string"),
  websiteTemplate: DS.belongsTo("App.WebsiteTemplate")

至于 id 的比较,您可以编写一个自定义的车把助手,它基本上看起来像这样:

Ember.Handlebars.registerHelper('equal', function(value1, value2, options) {
  if (value1 === value2) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

然后像这样使用它:

{{#equal webLayouts.id webLayout.id}}
  are equal
{{else}}
  not equal
{{/equal}}

在此处查看自定义助手的有效jsbin

希望对你有帮助。

【讨论】:

  • @JessicaDillon 你的意思是你有没有webLayout.id 传递给equal 助手的情况?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多