我在使用 Ember 和 Ember Data 处理服务器端验证时遇到问题。
当发生验证错误时,API 返回代码 422。然后 Ember 数据会触发becameInvalid
模型上的回调。
从这里开始,我不确定处理我遇到的错误的最佳方法是什么,以及如何使它们冒泡到视图中。
App.Challenge = DS.Model.extend Ember.Validations,
title: attr('string')
summary: attr('string')
# other attributes
becameInvalid: (errors) ->
# is it the place where I should handle the errors?
# how would I make the errors bubble up to the view here?
我有 2 个问题。
- 我不确定是否
becameInvalid
是处理错误的地方,如果是,如何让错误显示在视图中
- In
becameInvalid
, @get('isValid')
回报true
,这对我来说没有意义。
这是我应该处理错误的地方吗?
是的。但您可能根本不需要做任何事情。 Ember-data 期望您的 api 在其 json 响应中包含任何验证错误。该错误对象被传递给becameInvalid
挂钩并也保存为属性errors
在模型上。因此,如果您只想在视图中显示错误,那么执行以下操作可能就足够了:
{{input value=firstName}}<p class="inline-help">{{errors.firstName}}</p>
See: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js#L50-L61 https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js#L50-L61
在成为Invalid中,@get('isValid')返回true,这对我来说没有意义
同意这很奇怪。我认为这是一个绑定问题,就像在绑定更新之前运行的 BeenInvalid 钩子一样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)