简体   繁体   中英

Backbone model validation undefined attrs

So I've got my model which I'm trying to validate, according to the books this should work, however I'm receiving attrs as undefined.

validate: (attrs, options)->
    attrs

if I go ahead and do it this way:

validate: ->
    this.attributes 

I can access the model's attributes just fine however I don't think this is the recommended way to do it.

this is my model code:

class Todo extends Backbone.Model
    defaults: 
        title: 'default title'
        completed: false
    validate: (attrs, options)->
        attrs
myTodo new Todo
myTodo.validate()
//returns false because attrs is undefined 

what am I missing?

From the fine manual :

validate model.validate(attributes, options)

[...] By default validate is called before save , but can also be called before set if {validate:true} is passed.

So validate is meant to be called by Backbone, not directly by you. You're calling validate yourself:

myTodo.validate()

but not passing any arguments so attrs is undefined because, well, you didn't pass its value.

You're supposed to let Backbone call validate when you call myTodo.save() or myTodo.set(new_values, validate: true) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM