Implementing Backbone validation with form

469 Views Asked by At

I'm pretty new on Backbone and I have some issues (I think I still need some help from advanced user).

I added a form like this :

<form class="SectionContainer-Content container form-horizontal" role="form" id="addAquaForm">
    <div class="form-group">
        <label for="aquarium_name">Name</label>
        <input type="text" name="aquarium_name" id="aquarium_name" value="" placeholder="" class="form-control" />
    </div>
    <div class="form-group">
        <label for="aquarium_volume">Volume</label>
        <input type="text" name="aquarium_volume" id="aquarium_volume" value="" placeholder="" class="form-control" />
    </div>
    <div class="form-group">
        <label for="aquarium_type">Type : </label>
        <select class="form-control" id="aquarium_type">
            <option>first</option>
            <option>second</option>
       </select>
    </div>
</form>

Then I create a model :

var app = app || {};

app.Aquarium = Backbone.Model.extend({

  validation: {
    aquarium_name: {
      required: true,
      msg: 'Please enter a valid name'
    },
    aquarium_volume: {
      required: true,
      msg: 'Please enter a valid volume'
    },
    aquarium_type: {
      required: true
    }
  }
});

And then the view which pilote the form :

var AquariumFormView = Backbone.View.extend({
    tagName: "form",
    id: "addAquaForm",
    events: {
        'click #btn-new-aqua': "addAqua"
    },
    initialize: function () {
        // This hooks up the validation
        this.model = new pedia.Aquarium();
        Backbone.Validation.bind(this);
    },
    addAqua: function () {
        var data = this.$el.serializeObject();

        this.model.set(data);

        // Check if the model is valid before saving
        if (this.model.isValid(true)) {
            // this.model.save();
            alert('Great Success!');
        }
    },
    remove: function () {
        // Remove the validation binding
        Backbone.Validation.unbind(this);
        return Backbone.View.prototype.remove.apply(this, arguments);
    }
});

When I load my page, the view is not initialized but I have no idea how I could do it.

Somebody could give me some ideas?

Thanks :)

1

There are 1 best solutions below

0
bvoleti On

If you want to initialize the view when the page loads:

$(document).ready(function(){
 var view = new AquariumFormView ();
});