EmberJS 對(duì)象模型setter和getter

2018-01-03 17:21 更新

描述

Setter和Getter用于管理在computed屬性中聲明的變量的值。Ember.js set()方法計(jì)算程序中指定的特定條件的值。 Ember.js get()方法從setter中獲取值并顯示。

語(yǔ)句

App.Person = Ember.Object.extend({
   fullName: function(key, value, previousValue)
   {
      //setter and getter
   }.property('firstName', 'lastName')
});

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Setter and Getter</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/javascript">
         App = Ember.Application.create();

         App.Person = Ember.Object.extend({
           firstName: null,
           lastName: null,

           //Defining the fullName computed property function
           fullName: function(key, value, previousValue){
              //lenngth of argument must be > 5
              if (arguments.length > 5)
              {
                 //spliting the details and storing it into the nameParts array
                 var nameParts = value.split(/\s+/);
                 this.set('firstName', nameParts[0]);
                 this.set('lastName',  nameParts[1]);
              }
              return this.get('firstName') + ' ' + this.get('lastName');
           }.property('firstName', 'lastName')
         });
         var emp = App.Person.create({firstName:'Jhon', lastName:'DK'});//initializing the values for variable
         document.write("Details of the employee: <br>"+"Name: "+emp.get('firstName')+" LastName: "+emp.get('lastName'));//displaying the values by get() method
      </script>
   </body>
</html>

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:

  • 將上面的代碼保存在obj_set_get_cmp.html文件中

  • 在瀏覽器中打開此HTML文件。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)