Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Backbone.js model from validating when first added to collection

Tags:

backbone.js

Is there a way to suppress model validation in Backbone.js when a new model is first created?

In my app, I have a collection with an arbitrary number of models, which are represented as list items. The user can click a button on each item, which inserts a new empty item beneath the current item. The empty item is failing validation, obviously, because I don't want an empty item being saved later.

There's no way for me to know what sensible defaults might be when I'm creating the new item, so prepopulating the new model with valid data doesn't seem like an option.

Any suggestions?

Update: While working on a tangentially related problem, I realized that I was using Backbone.js version 0.9.0. When this version was released, other people had the same problem I was having, and they complained in this issue on GitHub.

Jeremy modified validation in 0.9.1 to fix this. Adding a (temporarily) empty model to a collection is a valid real-world usecase. You could handle the new, empty model in the view, but if you're managing a list of items like I am, that forces you to have a collection of item views (including the empty one) in addition to your collection of must-be-valid models. That's a really clunky workaround for an otherwise straightforward scenario. Glad this got fixed.

like image 858
Josh Earl Avatar asked Mar 09 '12 12:03

Josh Earl


2 Answers

You're not supposed to add invalid models :)

Digging a bit in Backbone source code (0.9.1 at least) showed that the mechanism can be circumvented by passing options to your add method:

var Mod=Backbone.Model.extend({
    validate: function(attrs,opts) {
        if (opts.init) return;
        return "invalid";
    }
});

var Col=Backbone.Collection.extend({
    model:Mod
});

var c=new Col();
c.add({},{init:true});

console.log(c.length);

A Fiddle: http://jsfiddle.net/jZeYB/

Warning : it may break things down the line.

like image 87
nikoshr Avatar answered Oct 11 '22 16:10

nikoshr


Do you need to add the model to the collection right away? I presume that validation fails because you add it to the collection immediately.

Instead, when the button is pressed you could just create the view and blank model. When the model validates you add it to the collection. You would need a submit button/mechanism on the new row to add it to the collection (which invokes validation automatically).

like image 26
Typo Johnson Avatar answered Oct 11 '22 15:10

Typo Johnson