EmberJS 计算属性

2018-01-03 17:10 更新

计算属性

计算属性允许将函数声明为属性。Ember.js在需要时自动调用计算的属性,并在一个变量中组合一个或多个属性

App.Car = Ember.Object.extend({
   CarName: null,
   CarModel: null,

   fullDetails: function() {
      return this.get('CarName') + ' ' + this.get('CarModel');
   }.property('CarName', 'CarModel')
});

在上述代码中, fullDetails 是调用 property()方法来呈现两个值(即CarName和CarModel)的计算属性。每当 fullDetails 被调用时,它返回 CarName CarModel

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Computed Properties</title>
      <!-- CDN's-->
      <script src="/attachements/w3c/handlebars.min.js"></script>
      <script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
      <script src="/attachements/w3c/ember.min.js"></script>
      <script src="/attachements/w3c/ember-template-compiler.js"></script>
      <script src="/attachements/w3c/ember.debug.js"></script>
      <script src="/attachements/w3c/ember-data.js"></script>
   </head>
   <body>
      <script type="text/javascript">
         App = Ember.Application.create();
         App.Car = Ember.Object.extend({
           //the values for below Variables to be supplied by `create` method
           CarName: null,
           CarModel: null,
           fullDetails: function(){
              //returns values to the computed property function fullDetails
              return ' Car Name: '+this.get('CarName') + ' Car Model: ' + this.get('CarModel');
             //property() method combines the variables of the Car
           }.property('CarName', 'CarModel')
         });

         var car_obj = App.Car.create({
            //initializing the values of Car variables
            CarName: "Alto",
            CarModel: "800",
         });
         //Displaying the Car information
         document.write("Details of the car: <br>");
         document.write(car_obj.get('fullDetails'));
      </script>
   </body>
</html>

输出

让我们执行以下步骤,看看上面的代码如何工作:

  • 将上述代码保存在 computed_prop.html 文件中。

  • 在浏览器中打开此HTML文件。

下表列出了计算属性的属性:

序号属性及描述
1 替代调用

它将一个或多个值传递给计算的属性,而不使用property()方法。
2 链接计算属性

链接计算的属性用于与一个或多个预定义的计算属性进行聚合。
3 动态更新

调用计算属性时动态更新。
4 设置计算属性

使用 setter和getter 设置计算的属性。
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号