Prevent Backbone.js model validation when first added to collection

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

In my application, I have a collection with an arbitrary number of models that are presented as list items. The user can click a button on each item that inserts a new blank item below the current item. An empty element does not check, obviously, because I do not want the empty element to be saved later.

There is no way to find out what reasonable default values ​​can be when I create a new element, so pre-preparing a new model using reliable data is not an option.

Any suggestions?

Update. While working on a tangent problem, I realized that I was using Backbone.js version 0.9.0. When this version was released, other people had the same problem that I encountered, and they complained about this problem on GitHub.

Jeremy modified the validation in 0.9.1 to fix this. Adding a (temporarily) empty model to the collection is the true reality in the world. You can handle a new empty model in a view, but if you manage a list of items like me, it forces you to have a collection of item views (including an empty) in addition to your collection of required records, valid models. This is a really clumsy decision about an alternative scenario. Glad this is fixed.

+5
source share
2

:)

Backbone ( 0.9.1), , , :

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/

: .

+3

? , , .

, , . , . / , ( ).

+2

All Articles