14

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?

3 Answers 3

24

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

Sign up to request clarification or add additional context in comments.

3 Comments

you can also observes('array.length')
Seems over-kill to use a library to want to do this task. I'm curious: Isn't there a vanilla js way to do the same?
As of Ember 2.0 you would use 'array.[]'
6

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

Comments

3

Check out this fiddle to see how to know exactly what object has been added or removed from the array using ArrayController.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.