Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I haven't tested this, but I'm pretty sure that all events on all models in a collection will be passed to and triggered by the collection as well. So you should be able to listen to the <code>error</code> event on the collection:</p> <pre><code>var cars = new Cars(); cars.bind('error', function() { console.log('Model not valid!') }) cars.add({'weight': -5}); </code></pre> <p><strong>Edit</strong>: Nope, this works for setting properties on existing models, but not on model creation. Ugh - it looks like there's no way to listen for this without overriding some part of the Backbone code. Models don't perform validation when they're initialized:</p> <pre><code>var car = new Car({weight: -5}); console.log(car.get('weight')); // no error, logs -5 </code></pre> <p>And while <code>collection.add()</code> does perform validation, it fails silently.</p> <p>If you use <code>collection.create()</code> instead of <code>collection.add()</code>, you can check, since <code>.create()</code> will return <code>false</code> on failure. But this will try to create the model on the server, which might not be what you want.</p> <p>So, I think the only way to do this is to override <code>collection._prepareModel</code> and trigger a custom event, like this:</p> <pre><code>Cars = Backbone.Collection.extend({ model: Car, _prepareModel: function(model, options) { model = Backbone.Collection.prototype._prepareModel.call(this, model, options); if (!model) this.trigger('error:validation'); return model; } }); var cars = new Cars(); cars.bind('error:validation', function() { console.log('Model not valid!') }); cars.add({'weight': -5}); // logs: 'Model not valid!' </code></pre> <p>Example here: <a href="http://jsfiddle.net/nrabinowitz/f44qk/1/" rel="nofollow">http://jsfiddle.net/nrabinowitz/f44qk/1/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload