get and set

At the core of Ember Data’s model records is an Ember.Object. This object definition contains the methods get and set. Unlike most languages, JavaScript does not force the use of getters and setters on object instances. Ember applies the concepts of getters and setters with these methods to force a function to be run when changing an object property. This allows Ember to add event triggers to set and make programmers be intentional when getting properties.

The get method takes a single argument, the property name, to retrieve the property value. Try it out in the app/routes/sightings.js model callback.

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    let record1 = this.store.createRecord('sighting', {
      location: 'Atlanta',
      sightedAt: new Date('2016-02-09')
    });
    console.log("Record 1 location: "  +  record1.get('location') );
    ...
    return [record1, record2, record3];
  }
});

Reload your browser. Make sure the DevTools are open and select the JavaScript console tab. You should see the log notes from Ember, ending with the line: “Record 1 location: Atlanta.”

Next, back in app/routes/sightings.js, set the value of record1’s location after creating the record and before you log the property.

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    let record1 = this.store.createRecord('sighting', {
      location: 'Atlanta',
      sightedAt: new Date('2016-02-09')
    });
    record1.set('location', 'Paris, France');
    console.log("Record 1 location: " + record1.get('location'));
    ...
    return [record1, record2, record3];
  }
});

Reload the browser and you will see that the console reflects the set value: “Record 1 location: Paris, France” (Figure 21.2).

Figure 21.2  set location

set location

These are basic examples of get and set. When setting a property on a model record, you can also assign other model records to the record property in order to create a relationship between two model records for properties that were defined with hasMany or belongsTo.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.173.238