0

嗨,我是骨干的新手。我正在尝试关注http://listen-dom-events-backbone.herokuapp.com/。我编辑了 html 以便输入三个属性:姓名年龄和职业

<form id="addPerson" action="">
        <input type="text" placeholder="Name of the person" id="name">
        <input type="text" placeholder="Age" id="age">          
        <input type="text" placeholder="Occupation" id="occ">
        <input type="submit" value="Add Person">
</form>
    <script id="personTemplate" type="text/template">
<span><strong><%= name %></strong> (<%= age %>) - <%= occupation %></span> 
<button class="edit">Edit</button>
<button class="delete">Delete</button>
    </script>

我的主干的验证是这样的。

App.Views.AddPerson = Backbone.View.extend({
el: '#addPerson',

events: {
    'submit': 'submit'
},

submit: function(e) {
    e.preventDefault();
    var newPersonName = $(e.currentTarget).find('input[type=text]').val();
    var newage = $(e.currentTarget).find(age).val();
    var newocc = $(e.currentTarget).find(occ).val();
    var person = new App.Models.Person({name: newPersonName, age: newage, occupation: newocc});

            // Only when the data exists it has to be added to the collection
            // This is what i tried

           // Method 1: 
    var attributes = person.attributes();
    validate: function(){
        if(attributes.newage ==null){alert("Please Enter Age")}
    if(attributes.newocc ==null){alert("Please enter occupation")}      
    }

            //Method 2
            var attributes = person.attributes();
    validate: function(attributes){
        if(attributes.newage !=null){person.set({age: newage});}
        if(attributes.newocc !=null){person.set({occupation: newocc});
            }

            // Only if everything above is correct this value should be returned
    this.collection.add(person);

}

});

我这样做是对的还是有问题?

4

1 回答 1

2

验证应该在模型中完成,这就是骨干的设计方式。如果您查看文档,您会看到模型中有一个validate方法、一个isValid方法和一个属性,当您覆盖该方法validationError时,它们开始变得有意义。validate因此,您validatePerson模型中的方法例如可以这样定义。

App.Models.Person = Backbone.Model.extend({
  // some other methods
  validate: function(attributes, options) {
    var errors = [];
    if(_.isEmpty(attributes.age)) {
      errors.push("age missing");
    }
    if(_.isEmpty(attributes.occupation)) {
      errors.push("occupation missing");
    }
    if(!_.isEmpty(errors)) {
      return errors;
    }
  }
});

然后,您将能够调用isValid您的模型,如果不是,您的validate方法返回的验证错误将通过该validationError属性获得。然后,您可以将您的提交方法更改为以下内容:

 submit: function(e) {
    e.preventDefault();
    if(this.model.isValid()) {
      // do what you want with your model
    } else {
      alert(this.model.validationError.join('\n'));
    }
  }
于 2013-09-14T16:14:27.550 回答