aw crud
aw crud

Reputation: 8891

How can I render Backbone.Model errors in a view without losing the invalid input?

I have a form in a Backbone View where user input is collected and stored in a model. Suppose the user entered information that violated the validation logic of the backing Model. How can I output these errors to the view without losing the invalid input?

Currently I just re-render the view and it replaces all input with that in the Model, but because the invalid inputs never got stored there they were lost.

Is there a simple way to capture all invalid data and re-render it all at once along with the error messages, or do I have to write custom jQuery to append nested error messages inside the form DOM without re-rendering it?

Upvotes: 0

Views: 973

Answers (1)

nikoshr
nikoshr

Reputation: 33344

Your view could track the error event raised by the validate method and render accordingly. For example,

var MView=Backbone.View.extend({
    initialize: function() {
        this.model.bind("error",this.renderErr,this);
        this.model.bind("change",this.render,this);
    },
    render: function() {
        console.log("ok");
    },
    renderErr: function(model,attrs) {
       //attr contains the attributes passed to validate
        console.log(attrs);
    }
});
var M=Backbone.Model.extend({
    defaults: {
        name:"locked",
        whatever:"value"
    },

    validate:function(attrs) {
        //returns the attributes being set. Will be used in the renderErr method
        if (attrs.name!="locked") return attrs;
    }
});

var m=new M();
var mv=new MView( {model:m} );
mv.render();
m.set({name:"err",whatever:"other"});
m.set({name:"locked",whatever:"other"});

Upvotes: 2

Related Questions