简体   繁体   English

Ember-data DS.Model中的私有变量

[英]Private variables in Ember-data DS.Model

I want to store a private variable on each DS.Model . 我想在每个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. 我已将其放置在initializer ,并且它按预期运行。

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. 这将进入Ember-cli插件,因此我希望它是最“最佳实践”。 (the _getPending / _setPending method are only to be used internally within the addon.) _getPending / _setPending方法只能在插件内部使用。)

Here are my 2 cents on this. 这是我的2美分。 I would say no it is not a good practice, but it should be okay since they are just Ember Objects. 我会说这不是一个好习惯,但是应该没关系,因为它们只是Ember Objects。 The question here is what is Ember data model used for? 这里的问题是Ember数据模型用于什么? 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. Ember模型API定义了可用于此目的的状态对象。 http://emberjs.com/api/data/classes/DS.Model.html Flags like isDeleted, isValid, isNew...gives all possible state. http://emberjs.com/api/data/classes/DS.Model.html诸如isDeleted,isValid,isNew等标志提供了所有可能的状态。

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 https://www.emberscreencasts.com/posts/102-ember-data-20-model-states-and-flags

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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