Note that there are some explanatory texts on larger screens.

plurals
  1. POClient Side validation on Backbone.js collection
    primarykey
    data
    text
    <p>I'm using backbone-on-rails gem and got the following: </p> <p>Model</p> <pre><code>class Crayons.Models.Color extends Backbone.Model validate: (attrs) -&gt; if attrs.colorname.length == 0 return "colorname can't be empty" </code></pre> <p>Collection</p> <pre><code>class Crayons.Collections.Color extends Backbone.Collection url: '/api/colors' </code></pre> <p>collection is created in a router</p> <pre><code> initialize: -&gt; @collection = new Crayons.Collections.Color() @collection.fetch() </code></pre> <p>Methods in ColorIndex</p> <pre><code> createCrayonId: (event) -&gt; event.preventDefault() val = new Crayons.Models.Color() val.on("error", @errorHandling); val.set(colorname: $('#new_color_name').val()) @collection.create colorid: val.get("colorname"); $('#new_color')[0].reset() errorHandling: (model, event) -&gt; alert(event) </code></pre> <p>I have a simple validation that shows an alert when the length is zero. However, after the alert box, the items are still being added to the collection because of <code>@collection.create colorid: val.get("colorname");</code> </p> <p>What can I do to stop the collection from adding the results in it when an error has been caught?</p> <p><strong>Update1</strong> Short term solution is below and it works but I'm unsure if its a correct way of doing things</p> <pre><code>ok = val.set(colorname: $('#new_video_url').val()) if ok @collection.create colorname: val.get("colorname"); </code></pre> <p><strong>Update2</strong></p> <pre><code>class Crayons.Collections.Colors extends Backbone.Collection url: '/api/videos' model: new Crayons.Models.Color() validate: (attrs) -&gt; if attrs.colorname.length == 0 return "colorname can't be empty" </code></pre> <p><strong>Correct way</strong> The validate function should be in the model and function that alerts the error should be initialized on the model. </p> <pre><code>class Crayons.Models.Color extends Backbone.Model initialize: -&gt; this.bind("error", @errorHandling) errorHandling: (model, event) -&gt; alert(event) validate: (attrs) -&gt; #your error validation goes here </code></pre> <p>Now the method in index is quite simple</p> <pre><code> createCrayonId: (event) -&gt; event.preventDefault() @collection.create colorname: $('#new_color_name').val() </code></pre>
    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.
 

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