简体   繁体   中英

Private variables in Ember-data DS.Model

I want to store a private variable on each DS.Model . Its purpose is to store a pending callback (in case I want to cancel it).

I have tried this (and it works):

DS.Model.reopen({
  init() {
    let _pending; // my private var

    this._getPending = () => _pending;                   // get private var
    this._setPending = callback => _pending = callback;  // set private var

    this._super(...arguments);
  }
});

I have placed this in an initializer , and it works as I expect it to.

My questions are: Is this a good practise? is it likely to mess anything up? ...and, is there a better way?

Personally, I'm happy with the way it works.. but I'm not sure if its the "Ember" way. This is going to go into an Ember-cli addon, so I would like it to be the most "best practise" as possible. (the _getPending / _setPending method are only to be used internally within the addon.)

Here are my 2 cents on this. I would say no it is not a good practice, but it should be okay since they are just Ember Objects. The question here is what is Ember data model used for? From doc it says:

"Models are objects that represent the underlying data that your application presents to the user."

By definition this is not what they are designed for, so just because you are able to it does not mean that you should use them like this.

Pending callback so it can be canceled? Ember model API has defined state objects that can be used for this purpose. http://emberjs.com/api/data/classes/DS.Model.html Flags like isDeleted, isValid, isNew...gives all possible state.

I would place them in router actions where they are easy tested with integration tests.

You can check this screencast that explains them:

https://www.emberscreencasts.com/posts/102-ember-data-20-model-states-and-flags

Hope it helps.

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