2

I want to delete all records of the model "Article" (around five pieces). I'm doing it like that:

CMS.ArticlesController = Em.ArrayController.extend
    deleteAll: ->
        @get("content").forEach (article) ->
            article.deleteRecord()

However, while executing, it says after three articles:

Uncaught TypeError: Cannot call method 'deleteRecord' of undefined

It works though when using a little delay:

CMS.ArticlesController = Em.ArrayController.extend
    deleteAll: ->
        @get("content").forEach (article) ->
            setTimeout( (->
                article.deleteRecord()
            ), 500)

Why is that?

(Im using Ember.js-rc.1 and Ember Data rev 11 together with the ember-localstorage-adapter by @rpflorence, but I don't think that matter since I didn't call commit() yet...)

Update 1

Just figured out it also works with Ember.run.once...

Update 2

I opened a GitHub issue: https://github.com/emberjs/data/issues/772

kraftwer1
  • 5,253
  • 10
  • 36
  • 54

2 Answers2

4

As discussed on GitHub, the forEach()-loop breaks, because it breaks the index while removing items.

The solution:

"Copy" it in another array using toArray():

@get("content").toArray().forEach(article) -> 
    article.deleteRecord()

The nicer approach, if there was a function like forEachInReverse, is to loop backwards, so even though items are removed, the missing index wouldn't hurt the loop.

kraftwer1
  • 5,253
  • 10
  • 36
  • 54
0

I still had issues with the above answer. Instead, I used a reverse for loop:

for(var i = items.length - 1; i >= 0; i--) {
   items.objectAt(i).destroyRecord(); // or deleteRecord()
} 

This destroys each item without disrupting the index.

NicholasJohn16
  • 2,390
  • 2
  • 21
  • 45