2

似乎没有考虑我的 Coffeescript 验证:

 class PokerRange extends Backbone.Model
    defaults:
        id:0
        cards:[[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12]]

    validate: (attributes) ->
        if attributes.id<0 then "id should be positive"

window.firstrange= new PokerRange id:5
console.log window.firstrange.toJSON()
window.firstrange.set("id",-4)
console.log window.firstrange.toJSON()

这是结果:

Object {id: 5, cards: Array[13]}
Object {id: -4, cards: Array[13]}
4

1 回答 1

2

我找到了原因,我只是忘记将选项传递给 set 方法 {validate:true}

    class PokerRange extends Backbone.Model
    defaults:
        id:0
        cards:[[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12],[0..12]]
    validate: (attributes) ->
        if attributes.id<0 then "id should be positive"

window.firstrange= new PokerRange id:5

window.firstrange.on "invalid", (model, error) ->  alert(error)


console.log window.firstrange.toJSON()
window.firstrange.set {id:-4}, {validate:true}
console.log window.firstrange.toJSON()
于 2013-02-02T15:28:38.537 回答