Search code examples
javascriptjquerybackbone.js

Highlight error card backbone js


What is the best way to highlight a error card view in backbone. At first i'm rendering 10 card like Ui where users input details in every card. When they click submit i'm checking all the details are filled correctly by parsing thorough collection->models. Right now i'm showing an alert if any model is incomplete . I want to highlight that model card with red background.


Solution

  • You can have the view listen to an event in the model, for example:

    CSS:

    .error{
      background:red;
    }
    

    Card view:

    Backbone.View.extend({
      initialize: function(){
        this.listenTo(this.model,'validationError',this.highlight);
      },
      highlight: function(){
        this.$el.addClass('error');
      }
    });
    

    then from where ever your validation the models, when a model has an error,

    model.trigger('validationError');
    

    If you're using validate method of model, you can just listen to invalid event on the view instead of custom event.