EmberJS中的非持久属性 [英] Non-persistent attributes in EmberJS

查看:78
本文介绍了EmberJS中的非持久属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为Ember 模型指定不持久的属性的方法吗?

Does anyone know of a way to specify for an Ember model an attribute which is not persisted?

基本上,我们正在加载与每个模型相关的一些元数据,并通过其中的 RESTAdapter 将数据发送到Ember该模型。可以在我们的应用程序中更改此元数据,但是可以通过使用AJAX调用来完成。通话成功后,我希望能够通过将模型更改为未提交并进行任何操作来在模型中更新此值,而Ember不会在这项业务中stick之以鼻

Basically, we're loading some metadata related to each model and sending that data to Ember via the RESTAdapter within the model. This metadata can be changed in our app, but is done via using an AJAX call. Once the call succeeds, I want to be able to update this value within the model without Ember sticking its nose in this business by changing the model to the uncommitted and doing whatever it does with transactions behind the scenes.

我也有一个问题,该元数据不是模型的数据库记录由 RESTAdapter 传递回服务器,该服务器不需要这些值。我使用的是RoR后端,因此服务器尝试批量分配受保护的属性时会出错,这些属性根本不是属性。我知道我可以清理服务器上收到的数据,但我希望客户端能够区分持久性数据和辅助数据。

I also have the problem that this metadata, which is not data from the model's database record, is passed by the RESTAdapter back to the server, which doesn't expect these values. I am using a RoR backend, so the server errors out trying to mass-assign protected attributes which aren't meant to be attributes at all. I know I can scrub the data received on the server, but I would prefer the client to be able to distinguish between persistent data and auxiliary data.

因此,对于原始数据问题:Ember-Data的 DS.attr('...')是否可以指定非持久属性?

So, to the original question: is there any alternative to Ember-Data's DS.attr('...') which will specify a non-persistent attribute?

推荐答案

PR 将get合并,就可以将属性标记为 readOnly 。但在此之前,有一些解决方法,例如在适配器中覆盖您的 addAttributes 方法并处理您的特殊属性,下面是一个示例,看起来像这样:

When this PR get's merged it will be possible to flag properties as readOnly. But till then there are some workarounds to this, e.g. overriding your addAttributes method in the Adapter and deal with your special properties, here an example how this could look like:

通过添加新选项 readOnly 来定义模型:

Define your Model by adding the new option readOnly:

App.MyModel = DS.Model.extend({
  myMetaProperty: DS.attr('metaProperty', {readOnly: true})
});

然后在适配器上:

App.Serializer = DS.RESTSerializer.extend({
   addAttributes: function(data, record) {
     record.eachAttribute(function(name, attribute) {
       if (!attribute.options.readOnly) {
         this._addAttribute(data, record, name, attribute.type);
       }
     }, this);
   }
 });

这是为了遍历模型的属性,以及当找到具有 readOnly 标志设置会跳过该属性。

what this does is to loop over the attributes of your model and when it find's an attribute with the readOnly flag set it skips the property.

我希望该机制适用于您的用例。

I hope this mechanism works for your use case.

这篇关于EmberJS中的非持久属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆