简体   繁体   中英

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.

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')
});

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM