gpt4 book ai didi

javascript - 验证失败时, Backbone 关系验证错误不返回

转载 作者:行者123 更新时间:2023-12-02 12:40:19 25 4
gpt4 key购买 nike

我将 Backbone 关系库升级到0.10.0。我在验证模型时遇到问题,回调方法中未定义validationError属性。此属性在以前的版本中有一个对象。

如果我更改了库文件中的代码,它可以工作,但我想询问是否有更好的方法或者是否有补丁,提前致谢。

我有一个带有验证方法的模型:

 define( [
'jquery',
'underscore',
'backbone',
'backbonerelational'

], function ( $, _, Backbone, Backbonerelational ) {
'use strict';

var MyModelR = Backbone.RelationalModel.extend( {

idAttribute: "itemId",
defaults: {
_hasServerSideError: false
},

validate: function ( attrs, options ) {
var error;
if ( !attrs.name ) {
error = {
name: 'name',
message: 'Please enter a name.'
};
}
return error ? error : false;
},


url: function () {
return "/myurl";
},


sync: function ( method, model, options ) {

if ( options.action ) {
options.emulateHTTP = true;
options.validate = true;
options.wait = true;
options.url = "/myurl" + options.action;
} else if ( method.toLowerCase() === "update" ) { //default action
options = options || {};
options.url = "/myurl";
}

Backbone.sync( method, model, options );
},

parse: function ( response, options ) {
//code here
}


} );
return MyModelR;
} );

我有一个监听无效事件的 View

  myView = Backbone.View.extend( {
initialize: function ( options ) {
this.listenTo( this.MyModelR , 'invalid', this.invalidHandler );
...code
},
invalidHandler: function ( model, error, options ) {
if ( options.validationError ) { //validationError has undefined value
showError(...)
}

});

如果我在第1899行调整backbone-relational.js库文件,它就可以工作,我想问是否有更好的方法来解决这个问题或者这是一个有效的缺陷?

if ( model && model.validationError ) {
options.validationError = model.validationError;//Added this line
this.trigger( 'invalid', this, attrs, options );
model = false;
}

最佳答案

https://github.com/jashkenas/backbone/blob/master/backbone.js#L727

签名是callback(model, error, options)options.validationErrorerror相同。示例:

var Album = Backbone.Model.extend({
validate: function(attrs, options) {
if (attrs.artist.toLowerCase() == 'nickelback') {
return "No way you're adding that here";
}
}
});
var album = new Album({artist: 'Nickelback'});
album.on("invalid", function(model, error, options) {
alert(options.validationError);
alert(error); //////////////////////////////////////////// <- look here
});
album.save()

关于javascript - 验证失败时, Backbone 关系验证错误不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34360111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com