【问题标题】:Access Parent Models In Ember在 Ember 中访问父模型
【发布时间】:2013-01-31 21:19:12
【问题描述】:

所以我想将我所有的 API 密钥存储在后端的配置文件中,这样我就不会将它们分散在各处。所以我想我可以在前端创建一个模型来在 /config 上执行 GET,然后我会返回一个配置对象,其中包含我需要的任何 API 密钥。所以我基本上是在尝试从 ApplicationRoute 访问模型。需要明确的是,请求现在发生,但我不知道如何从索引模板访问数据。我已经尝试过{{App.Config.apiKey}}{{apiKey}},试图在索引控制器中设置@get.controllerFor('application').get('model'),看看我是否可以查看值,但没有一个有效。我正在使用 Ember 1.0.0 .4pre。谢谢

所以我有这样的事情:

App = Ember.Application.create
   rootElement: '#app'

# Models
App.Store = DS.Store.extend
  revision: 11

App.User = DS.Model.extend
  firstName: DS.attr 'string'
  lastName: DS.attr 'string'
  accountType: DS.attr 'string'
  email: DS.attr 'string'
  _id: DS.attr 'string'
  password: DS.attr 'string'
  fullName: (->
    "#{@get('firstName')} #{@get('lastName')}"
  ).property('firstName', 'lastName')

App.Config = DS.Model.extend
  secret: DS.attr 'string'
  apikey: DS.attr 'string'

# Controller
# This is has validations for a form in it but I don't think its relivent
App.IndexController = Ember.ObjectController.extend()

# Routes
App.ApplicationRoute = Ember.Route.extend
  model: ->
    App.Config.find()

App.IndexRoute = Ember.Route.extend
  model: ->
    App.User.createRecord()

DS.RESTAdapter.configure "plurals", {
  config: "config"
}

App.Router.map ->
  @resource 'index'

我的模板看起来像这样:

<!--- index.html --->

<html>
  <head></head>

  <body>
    <div id="app"></div>
  </body>

</html> 

<!--- application.hbs --->
<div class="container">
  {{outlet}}
</div>

<--- index.hbs --->

<div>
  {{apiKey}} <!-- This is a value from the Config Model -->
  {{firstName}} <!-- This is a value from the User Model -->
</div>

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    将您的 ApplicationController 明确定义为 ObjectController

    App.ApplicationController = Ember.ObjectController.extend()
    

    然后在您的 ApplicationRoute 中将控制器的内容设置为配置对象

    App.ApplicationRoute = Ember.Route.extend
      setupController: (controller, model) ->
        this._super(controller,model);
        controller.set('content',App.Config.find(1));
    

    或者,在索引控制器中设置配置,例如

       App.IndexRoute = Ember.Route.extend({
         setupController: function(controller,model) {
           this._super(controller,model);
           controller.set('config',App.Config.find(1));
         }
        })
    

    然后在你的模板中

    <div>
      {{config.apiKey}} <!-- This is a value from the Config Model -->
      {{config.firstName}} <!-- This is a value from the User Model -->
    </div>
    

    使用第一种方法查看有效的jsfiddle

    您可以了解ember here支持的不同类型的控制器

    【讨论】:

    • 如果这有帮助的话,这里是项目的 repo。 github.com/chadhietala/rentr
    • 你能设置一个 jsfiddle 吗?
    • 这是一个小提琴jsfiddle.net/wQJrg/1。它不反映您的任何建议。
    • 其实这真的不能回答我原来的问题。我希望能够从索引模板内部访问配置模型。
    • 在 IndexRoute 中做同样的事情。这是另一个带有更新的 jsfiddle jsfiddle.net/wQJrg/4
    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    相关资源
    最近更新 更多