繁体   English   中英

在Ember.js的屏幕上显示Ember.Object

[英]Display Ember.Object on the screen in Ember.js

我在Ember绿了。 我遵循了快速入门,并运行了以下命令:

ember new ember-quickstart
ember g route index

我用索引路由创建了一个基本的Ember应用程序。 我想使用此路线在屏幕上显示日期。 因此,我在其中创建了一些EmberObjects。

应用程序/路由/ index.js

import Object from '@ember/object';
import Route from '@ember/routing/route';

function getCompaniesJSON() {
  return [
    {
      "title": "Danone",
      "upvotes": 92,
      "downvotes": 62
    },
    {
      "title": "Bakoma",
      "upvotes": 58,
      "downvotes": 68
    },
    {
      "title": "Zott",
      "upvotes": 62,
      "downvotes": 54
    },
    {
      "title": "Jana",
      "upvotes": 72,
      "downvotes": 56
    }
  ];
}

function totalVotes(company) {
  return company.get('upvotes') + company.get('downvotes');
}

var Company = Object.extend({
  score: function() {
    return (this.get('upvotes') * 100 / totalVotes(this)).toFixed(2);
  }
});

var AppModel = Object.extend({
  topCompanies: function() {
    return this.get('companies').sort(function(a,b) {
      return totalVotes(b) - totalVotes(a);
    }).slice(0, 3);
  }.property('companies.@each.upvotes', 'companies.@each.downvotes')
});

var appModel = AppModel.create({
  companies: getCompaniesJSON().map(function(json) {
    return Company.create(json);
  })
});

export default Route.extend({
  topCompanies: appModel.topCompanies
});

应用程序/模板/ index.hbs

<ul>
{{#each topCompanies}}
  <li>{{title}} {{score}}%</li>
{{/each}}
</ul>

上面的代码什么都不显示。 控制台中没有错误。 我想在屏幕上显示topCompanies,但我不知道如何正确传递此变量。 路线是正确的地方吗? 还是我应该使用组件/控制器?

该模板绑定到controller ,而不是route 但是,您的route应从model挂钩中返回model

因此,您可以执行以下操作:

export default Route.extend({
  model() {
    return appModel.topCompanies
  }
});

但是随后您的模型在控制器和模板上而不是topCompanies上被称为model 要解决此问题,请将其添加到您的控制器( ember g controller index ):

topCompanies:computed.alias('model')

可以导入computedimport {computed} from '@ember/object';


接下来,您将遇到未显示score的问题。 那是因为您将其声明为函数,而不是计算属性。 因此,您应该将其更改为:

score: computed('upvotes', 'downvotes', function() {
  return (this.get('upvotes') * 100 / totalVotes(this)).toFixed(2);
}),

您也可以执行相同的操作,但是强烈建议您不要这样做,因为它的语法旧:

score: function() {
  return (this.get('upvotes') * 100 / totalVotes(this)).toFixed(2);
}.property('upvotes', 'downvotes'),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM