ember.js - Ember.js 中基于模型状态切换 View 模板

标签 ember.js

我的 Ember.js 应用程序中有一个通知框,它会根据 Status 模型的值更改文本、样式和按钮。 如何只切换通知框的 View (或模板)?我不想 transitionTo 因为页面的其余部分不应该更新,只有那个通知框。

我有一个 JSFiddle with a complete example .但这里是相关的部分:

主模板将呈现通知栏(“statusState”)和常规 View 数据。

<script type="text/x-handlebars" data-template-name="status">
  {{render "statusState" content}}
  <p>
  Other information not related to the status state, but still related to status goes here.
  </p>
  {{outlet}}
</script>

每个 Status 状态(“pending”、“ready”、“finished”)都有一个单独的模板:

<script type="text/x-handlebars" data-template-name="status/pending">
  <div style="background-color: grey">
    The status is pending.
  </div>
</script>

<script type="text/x-handlebars" data-template-name="status/ready">
  <div style="background-color: blue">
  The status is ready.
  </div>
</script>

<script type="text/x-handlebars" data-template-name="status/finished">
  <div style="background-color: green">
    The status is finished.
  </div>
</script>

Status对象没什么特别的,属于StatusController:

App.StatusRoute = Ember.Route.extend({
  model: function() {
    return App.Status.create();
  }
});

App.Status = Ember.Object.extend({
  value: 0
});

我的第一次尝试是在 Status 的值发生变化时更改 View 的模板名称。但这感觉很老套,甚至似乎没有响应 Status 值的变化:

App.StatusStateView = Ember.View.extend({
  templateName: function() {
    var templateName = 'status/pending';
    var value = this.get('controller.model.value');
    if (value === 1) {
      templateName = 'status/ready';
    }
    else if (value === 2) {
      templateName = 'status/finished';
    }
    return templateName;
  }.property('controller.model.value')
});

简而言之,我如何根据具有 2 个以上选择的模型值更改页面的一部分的 View 或模板?

最佳答案

以下是我的处理方法。将 bool 计算属性添加到模型或 Controller ,并使用带有 {{#if }} 助手的单个模板。例如

App.Status = Ember.Object.extend({
  value: 0,
  ready: function(){
     return this.get('value') === 1;
  }.property('value'),
  finished: function(){
     return this.get('value') === 2;
  }.property('value'),
  pending: function(){
     var value = this.get('value');
     return value !== 1 && value !== 2;
  }.property('value')
});

在一个模板中:

{{#if pending}}
  I'm pending
{{/if}}
{{#if ready}}
  I'm ready!
{{/if}}
{{#if finished}}
  I'm finished.
{{/if}}

关于ember.js - Ember.js 中基于模型状态切换 View 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072557/

相关文章:

javascript - Ember Js : Common RESTAdapter

javascript - 如何在 ember-file-upload 中执行组件操作而不是路由操作

ember.js - Ember : simple way to set focus in a field

javascript - EmberJS Action - 当包装在 `actions` 中时从另一个 Action 调用一个 Action

ember.js - 将参数传递给 ember 插件源代码的最佳方式

ember.js - 如何检查本地存储中是否已存在 Ember Data 模型实例?

javascript - 在Ember CLI构建的Ember JS中,如何调用不同 Controller 上的方法?

html - 在 Ember.js 中使用 HTML anchor

javascript - Ember.js 和 ArrayController

ember.js - `needs` 渲染模板前不等待数据返回