John T
John T

Reputation: 237

Ember.js - Limit models in the store?

Is there a way to limit the amount of models that exist in the Ember Data store? The use case for this is a chat app. It cannot be slowly eating away at the browser's memory as more and more Message models fill up. Preferably the oldest model would delete itself if there are more than 100 in store.

Upvotes: 3

Views: 558

Answers (2)

jfs
jfs

Reputation: 81

In Kingpin2k's answer, instead of message.deleteRecord() I would use message.unloadRecord() which would have almost the same effect locally (client side), but without any risk that the record be deleted from the server (this could happen with deleteRecord e.g. if a there were a call to message.save() afterwards, which could happen "accidentally" in complex apps).

In other words, deleteRecord should be used when the client wants to delete the record server side.

Upvotes: 1

Kingpin2k
Kingpin2k

Reputation: 47367

You can watch all the records of a type in the store, and delete them whenever there are more than you want. This could really live on any controller/route...

App.MessagesRoute = Em.Route.extend({
  allMessages: function(){
    return this.store.all('message');
  }.property(),
  messageCount: Em.computed.alias('allMessages.length'),
  watchSize: function(){
    var cnt = this.get('messageCount'),
        messages;
    if(cnt>100){
       messages = this.get('allMessages').sortBy('messageDate').toArray().slice(100);
       messages.forEach(function(message){
         message.deleteRecord();
       });
    }
  }.observes('messageCount')
});

Upvotes: 4

Related Questions