如果子模型无效,则阻止保存?
我有一个巴士模型,它有一个嵌套的路线模型。
class Busables.Models.Bus extends Backbone.Model
url: '/buses'
defaults:
route: new Busables.Models.Route()
然后我有一个整体错误视图,它监听总线模型及其路线的 error
事件。
class Busables.Views.Errors extends Backbone.View
el: '#error-area'
template: JST['shared/error']
# model in this instance is a bus
initialize: ->
@model.get('route').bind 'error', this.routeError, this
@model.bind 'error', this.busError, this
因此,当用户在页面上提交表单时,我保存总线的属性,并将其发送到服务器:
class Busables.Views.NewBus extends Backbone.View
...
saveBus: (event) ->
event.preventDefault()
@model.save {
seats: this.$('#bus_seats').val(),
}, {
success: (model, response) ->
console.log "Success. The model and response: ", model, response
window.location.href = "/buses/#{response.id}"
}
所以问题是,在保存总线时如何触发嵌套路由的验证?
I have a bus model, which has a nested route model.
class Busables.Models.Bus extends Backbone.Model
url: '/buses'
defaults:
route: new Busables.Models.Route()
Then I have an overall error view which listens to the error
events of the bus model and it's route.
class Busables.Views.Errors extends Backbone.View
el: '#error-area'
template: JST['shared/error']
# model in this instance is a bus
initialize: ->
@model.get('route').bind 'error', this.routeError, this
@model.bind 'error', this.busError, this
So, when the user submits a form on the page, I save an attribute of the bus, and send it to the server:
class Busables.Views.NewBus extends Backbone.View
...
saveBus: (event) ->
event.preventDefault()
@model.save {
seats: this.$('#bus_seats').val(),
}, {
success: (model, response) ->
console.log "Success. The model and response: ", model, response
window.location.href = "/buses/#{response.id}"
}
So the question is, how do I trigger validation of the nested route while I'm saving the bus?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要重写总线上的
validate
方法,并让它调用嵌套路由的验证。每当更新或保存模型时都会调用
validate
方法,这使您有机会防止无效数据进入模型或返回服务器。如果您从validate
方法返回任何非 false 值,则 validate 方法将阻止保存或属性更新。我还建议查看 Backbone-Relational 插件。它为您处理了很多事情,如果您自己这样做,您很可能会重写该插件中已有的代码。
You'll need to override the
validate
method on your Bus and have it call the validation for the nested route.The
validate
method is called any time your model is updated or being saved, giving you an opportunity to prevent invalid data from making it's way in to your model or back to the server. If you return any value fromvalidate
method that is not falsy, then the validate method will prevent the save or attribute update.I would also recommend looking at the Backbone-Relational plugin. It handles a lot of this for you, and chances are you'll be re-writing code that is already available in that plugin, if you do this yourself.