Search code examples
ember.jsember-data

Inject additional data to ember model


I want inject current user to my topic model and make some checks.

Example:

export default DS.Model.extend({
    currentUser: Ember.inject.service('session-account'),
    text: DS.belongsTo('string'),
    userId:   DS.attr('number'),
    isMine: function(){
        return this.get('currentUser.data.id') == this.get('userId')
    }.property()
}

Question: Is it preferable approach to do this logic? Also I'm interesting about performance of this approach, inject service to each row may cause performance degradation?


Solution

  • You definitely can do this, but depending on what you have in currentUser.data it might not be optimal, or not produce the expected result. If currentUser.data is a ProxyObject (DS.PromiseObject) or promise it can cause the computed property to be counted more times then you intend it.
    Moreover object.get('x.y.z') can produce unintended results especially if x or y are promises, be careful with chaining properties in get

    If currentUser.data is DS.PromiseObject you are better of implementing the computed property like this:

    export default DS.Model.extend({
        currentUser: Ember.inject.service('session-account'),
        text: DS.belongsTo('string'),
        userId:   DS.attr('number'),
        isMine: Ember.computed('currentUser.data.id', 'userId', function() {
             model = this;
             promise = new Ember.RSVP.Promise(function(resolve, reject){
                 model.get('currentUser.data').then(function(currentUserData){
                    resolve(currentUserData.get('id') === model.get('userId')) 
                 }).catch(function(reason){
                    reject(reason)
                 })
             })
    
             return DS.PromiseObject.create(
                 promise: promise
             )
        })
    })