Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe adding element to array

Tags:

ember.js

I want to observe adding element to array. below is test program.

<!-- library load -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.6.1.min.js"%3E%3C/script%3E'))</script>
<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-0.9.5.min.js"></script>

<script type="text/x-handlebars">
  {{#each App.ArrayController.array}}
    {{foo}}
  {{/each}}
  <button onclick="App.ArrayController.addElement();">add</button>
</script>
<script type="text/javascript">
  var App = Em.Application.create();
  App.ArrayController = Em.Object.create({
    array: [{foo:1}, {foo:2}, {foo:3}],
    addElement: function() {
      this.array.pushObject({foo:4});
    },
    elementAdded: function() {
      alert('ok'); // not invoked...
    }.observes('array')
  })
</script>  

But when call addElement, elementAdded is not invoked... How do I observe adding element?

like image 443
arumons Avatar asked Feb 28 '12 17:02

arumons


People also ask

How do you add an element to an array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

How do you add an element to an array in array?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.


2 Answers

use observes('array.@each') instead. jsfiddle code is here

like image 62
Amareswar Avatar answered Sep 24 '22 01:09

Amareswar


You can use Ember.ArrayController and overwrite the arrayDidChange function And optionaly call other methods from ther.

<!-- library load -->
<script type="text/x-handlebars">
  {{#each App.ArrayController.array}}
    {{foo}}
  {{/each}}
  <button onclick="App.ArrayController.addElement();">add</button>
</script>
<script type="text/javascript">
  var App = Em.Application.create();
  App.arrayController = Ember.ArrayController.create({
    content: [{foo:1}, {foo:2}, {foo:3}],
    addElement: function() {
      console.log(this);
      var array = this.get('content')
      array.pushObject({foo:4});
      // this.set('array', array);
    },
    elementAdded: function() {
      console.log('ok'); // not invoked...
    }.observes('array'),

    arrayDidChange: function(item, idx, removedCnt, addedCnt) {
      this.elementAdded();
      this._super(item, idx, removedCnt, addedCnt);
    }
  });
</script>

And you can use Observers

like image 29
user773093 Avatar answered Sep 23 '22 01:09

user773093