Javascript Backbone.js集合无法获取无效的模型
我向模型添加了验证,集合无法获取无效的模型。(顺便说一句,我使用coffeescript,因此示例都在coffeescript中) 有人知道解决办法吗?下面的方法不起作用Javascript Backbone.js集合无法获取无效的模型,javascript,ruby-on-rails-3,backbone.js,coffeescript,Javascript,Ruby On Rails 3,Backbone.js,Coffeescript,我向模型添加了验证,集合无法获取无效的模型。(顺便说一句,我使用coffeescript,因此示例都在coffeescript中) 有人知道解决办法吗?下面的方法不起作用 collection = new UserCollection collection.fetch({ silent: true success: -> console.log('collection.models:', collection.models) }) 更新1 我有很多没有手机号码的用户 用
collection = new UserCollection
collection.fetch({
silent: true
success: ->
console.log('collection.models:', collection.models)
})
更新1
我有很多没有手机号码的用户
用户集合:
class UserCollection extends Backbone.Collection
url: ->
app.routes.users_url
用户模型:
class User extends Backbone.Model
idAttribute: '_id'
defaults: {
"email": null
"mobile": null
"loc": null
}
url: ->
app.routes.users_url + '/' + (@id || '')
validate: (attrs) ->
if !attrs.email
return "Email address must be provided"
if !attrs.name
return "Name must be provided"
if !attrs.mobile
return "Mobile number must be provided"
if @isNew() and attrs.password != undefined
if !attrs.password
return "Password must be provided"
if attrs.password != attrs.password_confirmation
return "Passwords do not match"
model: User
更新2
好的,我通过破解backbone.js临时修复了它
它发生在函数\u prepareModel中
我改变了这一行:
if (model.validate && !model._performValidation(attrs, options)) model = false;
if (!options.silent && model.validate && !model._performValidation(attrs, options)) model = false;
进入这一行:
if (model.validate && !model._performValidation(attrs, options)) model = false;
if (!options.silent && model.validate && !model._performValidation(attrs, options)) model = false;
这不是一个解决方案,所以我保留这个问题
"I added a validation to a Model and a Collection wont fetch the models who arent valid.
(Btw I use coffeescript so the examples are in coffeescript)"
如果您的模型未进行验证,则您的模型或验证存在问题
"I have a lot of users without a mobile number."
在验证过程中,您有:
if !attrs.mobile
return "Mobile number must be provided"
您可以在集合中定义一个parse函数来记录来自服务器的模型(parse()从fetch()获得原始响应)
或者,您可以从验证中删除验证是否存在移动电话号码的行,因为您不知道用户是否有移动电话号码
为了涵盖所有基础,为fetch()定义一个错误函数应该可以帮助您:
collection.fetch({
silent: true
success: ->
console.log('collection.models:', collection.models)
error: (collection, response) ->
console.log('response')
})
验证模型时,请检查是否存在
model.silent
,并仅在该模型不存在时进行验证
因此,当您要获取模型时,请执行以下操作:
var test = new MyModel({ id: '123', silent: true });
// in your Model validate function
validate: function(attrs) {
if (!attrs.silent) {
// validate logic here
}
}
然后你可以取回模型。获取模型后,您可以取消静音。您是否也尝试过传递
错误
回调?它被调用了吗?你能发布你的模型和验证代码吗?奇怪。。。如果传入silent:true
标志,Collections.fetch函数将不会运行验证器。您确定正在调用验证
函数吗@请检查我的更新2。该函数在_prepareModel中调用。即使你通过了沉默:真的。这可能是一只虫子吗?还是我做错了什么?也许在github上为此打开一个问题是好的问题是,即使我添加了silent:true,集合也没有获取它们。值得注意的是,集合中的parse
方法不一定传递带有results
键的对象。这取决于您使用的API。twitterapi传递一个带有results
键的对象,但普通主干应用程序只传递一组模型。