appceleratorbackbone.js-collectionsappcelerator-alloy

How do you delete all models in an Alloy Collection


From within a controller function, how do you delete all the models in an Alloy Collection. The collection is using properties sync adapter. I think the backbone reset method is the way to go but I could not make it work.


Solution

  • The quickest way for me was to run destroy() on every model. To do this quickly you can use underscore (build in) like this:

    _.invoke(Alloy.Collections.library.toArray(), 'destroy');
    

    or even extend the model.js

    extendCollection: function(Collection) {
            _.extend(Collection.prototype, {
                // extended functions and properties go here
                dump: function() {
                    // get all models
                    return this.models;
                },
                clear: function() {
                    // remove/destroy all models
                    _.invoke(this.toArray(), 'destroy');
                }
            });
    
            return Collection;
    }
    

    and run Alloy.Collections.library.clear();

    Pro Tip: you can always search for things like delete all models in backbone and use most of the results right away since it is using backbone in the background.