Question

I need the console to notify when a song is created without a title I tried this but the console shows nothing. A syntax error isn't thrown neither

var Song = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        track: 0
    },
    initialize: function()
    {
        this.on("change:title", function(){
            console.log("title changed");
        }); 

        this.on("error",function(model,error)
        {
            console.log(error);
        });
    },
    validate: function(attribs)
    {   
        if (attribs.title === "default title") 
        {
            return "please set a title";
        }
    }
});

var song1 = new Song;
song1.set({ track: 1});
Was it helpful?

Solution

Backbone 1.1 slightly changed how validation works :

Model validation is now only enforced by default in save — not in set unless the {validate:true} option is passed. Model validation now fires an "invalid" event instead of "error".

Try

song1.set({track: 1}, {validate: true});

and change your listener to

this.on("invalid", function(model, error) {
    console.log(error);
});

And a demo http://jsfiddle.net/nikoshr/z2p9T/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top