简体   繁体   中英

Set model attribute during validation in Backbone

I have a model as

var Info = Backbone.Model.extend({
    url: '',
    defaults: {
       username: '',
       email: '',
       error: ''
    },
    initialize: function(){
        console.log('Obj created');
    },
    validate: function(attr){
        if(!attr.username){
           attr.error = 'Username cannot be empty';
        }
    }
});

View

var model = new Info();
var View1 = Backbone.View.extend({
     model: model,
     initialize: function(){
        this.render();
     },
     render: function(){
        var template = _.template($('#App1').html());
        this.$el.html(template);
     },
     'events': {
         'click #btn1': 'submit'
     },
     submit: function(){
          var obj = {
              username: $('#username').val(),
              email: $('#pwd').val)
          };
          this.model.save();
     }
});

Here I want to set model.set({error: 'Message goes here'}) during validate event.

However, validate only returns true / false. Is there a way we can set the value in the validate method.

You can set an error property inside validate() function:

this.set('error', 'Message goes here')

Once set, error message will be accessible via this.model.get('error') from within view object code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM