0
votes

I have a backbone view that among other things it performs an ajax call that gets user's inputs for dates (from and to, from js datepicker widget), the corresponding django view queries the db according to these inputs and returns the new json-ed data. Now, on success I try to append the new data to the el but the el also keeps the initial ones. What's more, every time I select new dates a new div is added below the former one on the template. How am I supposed to solve this?

More or less I'm doing sth like this:

` TestView = Backbone.View.extend ({ template: _.template($("#test-template").html()), url: $("#test-url").data('url'),

render: function() {
  var template = this.template;
  var url = this.url;
  var el = $(this.el);
  var _this = this;

  var currentDate = new Date();
  var day = currentDate.getDate();
  var month = currentDate.getMonth() + 1;
  var year = currentDate.getFullYear();
  cur_date = month + "/" + day + "/" + year;

  var m = month - 1 ;
  prev_date = m + "/" + day + "/" + year;

  data_send = {period_from: prev_date, period_to:cur_date};

  $.get(url, data_send, function(data) {
    var pigs = $.parseJSON(data);
    el.append(template(pigs));
    _this.event();
    $( ".date-popup" ).datepicker();
  });
  return this;
},

event: function(){
  _this = this;
  var $to = $('#to_id');
  var template = this.template;
  var url = this.url;
  var el = $(this.el);
  $to.on('change', function(event) {
     var from = $('#from_id').val();
     var to = $('#to_id').val();
     $.ajax({
        type:"GET",
        url :url,
        data: {
            period_from: $('#from_id').val(),
            period_to: $('#to_id').val()
        },
        datatype:"json",
        error:function(data){alert('Error:'+data);},
        success:function(data){
            var pigs = $.parseJSON(data);
            el.append(template(pigs));
            _this.event();
        }
      });
   });
 }

});`

1

1 Answers

0
votes

If you do not want the old data to be displayed, then may be using el.html(template(pigs)) instead of el.append(template(pigs)) would help.