使用表单实现骨干验证



我是Backbone的新手,我有一些问题(我想我仍然需要高级用户的帮助)。

我添加了这样一个表单:

<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>

然后我创建了一个模型:

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
    }
  }
});

然后是引导形式的视图:

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);
    }
});

当我加载页面时,视图没有初始化,但我不知道该怎么做。

有人能给我一些想法吗?

感谢:)

如果您想在页面加载时初始化视图:

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

相关内容

  • 没有找到相关文章

最新更新