Open In App

Ember.js ArrayProxy addObserver() Method

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by many websites, including Square, Discourse, Groupon, Linked In, Live Nation, Twitch, and Chipotle.

The addObserver() method is used to register an observer for a property. The observer will call the method whenever the value of the property changes.

Syntax:

addObserver( key, target, method, sync );

Parameters:

  • key: It name of the property for which the observer will register. 
  • target: It is an object which invokes whenever a property changes. 
  • method: It is a method that invokes on value change of property. 
  • sync: This parameter indicates whether the observer is synced or not.

Return: Observable.

Steps to Install and Run Ember.js:

Step 1: To run the following examples, you will need to have an ember project with you. To create one, you will need to install ember-cli first. Write the below code in the terminal:

npm install ember-cli

Step 2: Now, you can create the project by typing in the following piece of code:

ember new <project-name> --lang en

To start the server, type:

ember serve

Example 1: Type the following code to generate the route for this example:

ember generate route test1
  • app/components/arr.js

Javascript




import Component from '@glimmer/component';
import Ember from 'ember';
import { action, without, set, get } from '@ember/object';
export default Ember.Component.extend({
    value: 'Oxygen',
    init() {
        this._super(...arguments);
        this.addObserver('value', this, 'change');
 
    },
    change() {
        console.log('Value changed ')
    },
    list: [
        'Black Panthar',
        'Source_Code',
        'Infine',
        'Tenet',
        'SpiderHead',
        'The_Thing',
        'A_Quiet_Place',
        'The_Invisible_Man',
        'Looper',
        'Avtar',
    ],
 
 
@action
remove(data) {
    this.list.set('[]', this.list.without(data));
},
@action
print(){
    let ans = this.list.get('[]');
    alert(ans.join('\n'))
}
 
})


  • app/components/arr.hbs

HTML




<ul>
    <h3>{{yield}} </h3>
      {{#each this.list as |item|}}
        <li>{{item}}</li>
      {{/each}}
</ul>
<br />
{{input value=this.value}}
<br />
<input
    type="button"
      id="check-atIndex"
      value="Remove"
      {{action "remove" this.value}}
/>
<br /><br />
<input
    type="button"
      id="print-item"
      value="Print All Items"
      {{action "print"}}
/>


  • app/templates/test1.hbs

HTML




<Arr> <h3>Movies List : </h3></Arr>


Output:

Ember.js EmberObject addObserver() Method

Example 2: Type the following code to generate the route for this example:

ember generate route test2
  • app/components/arr2.js

Javascript




import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import Ember from 'ember';
 
let Student = Ember.Object.extend({
    // these will be supplied by `create`
    firstName: null,
    lastName: null,
 
    fullName: Ember.computed('firstName', 'lastName', function () {
        return `${this.firstName} ${this.lastName}`;
    }),
 
    Changed: Ember.observer('fullName', function () {
        console.log(`fullName changed to: ${this.fullName}`);
    }),
});
 
export default Ember.Component.extend({
    students: [
        Student.create({
            firstName: 'Balit',
            lastName: 'stark',
            Id: 'stu2',
        }),
        Student.create({
            firstName: 'Permu',
            lastName: 'scott',
            Id: 'stu0',
        }),
        Student.create({
            firstName: 'Sam',
            lastName: 'melo',
            Id: 'stu1',
        }),
        Student.create({
            firstName: 'Pokhu',
            lastName: 'Verma',
            Id: 'stu3',
        }),
        Student.create({
            firstName: 'Tanu',
            lastName: 'Agrawal',
            Id: 'stu4',
        }),
        Student.create({
            firstName: 'Arabh',
            lastName: 'Singh',
            Id: 'stu5',
        })],
@tracked
value: 'Pokhu',
 
@tracked
value2: 'Pokhraj',
 
@action
print(data1, data2) {
    let ans = this.students.find((item) => item.get('firstName') == data1)
    ans.set('lastName', data2)
}
})


  • app/components/arr2.hbs

HTML




{{yield}}
<table>
    <tr>
        <th>Name</th>
        <th>Id</th>
      </tr>
      {{#each this.students as |detail|}}
        <tr>
            <td>{{detail.fullName}}</td>
              <td>{{get detail "Id"}}</td>
        </tr>
      {{/each}}
</table>
<br />
{{input value=this.value}}
{{input value=this.value2}}
<br />
<input
    type="button"
      id="set-code"
      value="Update Student details"
      {{action "print" this.value this.value2}}
/>


  • app/templates/test2.hbs

HTML




<Arr2><h3>Student's List :</h3></Arr2>


Output:

Ember.js EmberObject addObserver() Method

Reference: https://api.emberjs.com/ember/4.6/classes/ArrayProxy/methods/addObserver?anchor=addObserver



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads