Rommel Castro
Rommel Castro

Reputation: 460

jQuery DOM event not working on Backbone View

i have a view that every time is called re-renders the elements in the view, here is a code's piece:

Project.Views.CheckinScheduledView = Backbone.View.extend({
tagName: 'div',
id:'CheckinScheduledView',
className:'section',
checkinsHtml: '',

initialize: function() {
    _.bindAll(this);

    this.checkinsCollections = new Project.Collections.Checkins();

    this.checkinsCollections.on('reset', this.render);
    this.checkinsCollections.fetch();
},

events: {
    'click .scheduled_checkin a':'deleteCheckin'
},

render: function() {
    var that = this;

    // HERE IS THE PROBLEM
    if($('li.scheduled_checkin').length) {
        $('li.scheduled_checkin').each(function() {
            $(this).css('display','none').empty().remove();
        });
    }



    if(Project.InfoWindow.length) {
        Project.InfoWindow[0].close();
    }

    _.each(this.checkinsCollections.models, function(item) {
        that.renderLocation(item);
    });

    $(this.el).html(this.template());
    this.renderCheckins();
    return this;
},

refreshData: function() {
    this.checkinsCollections.fetch();
}

this is a case:

  1. open home page
  2. click on checkIn (current view code)
  3. go back to home
  4. the view render but adds the items to the list

images

First time i load the view first time i load the view

let's say that i go to another view and now i come back to this view let's say that i go to another view and now i come back to this view

and again :( and again

Upvotes: 1

Views: 132

Answers (1)

From your jsfiddle without working HTML example, at this function:

renderLocation: function(location) {
    this.checkinsHtml = this.checkinsHtml+'<li class="scheduled_checkin"><a data-id="'+location.attributes.scheduleId+'" href="#/checkin/" title="Delete: '+location.attributes.description+'">'+location.attributes.title+'</a></li>';
}

I guess that you forgot to reset this.checkinsHtml when re-render the view.

Edit: For the better way, you should render html from the template.

Example using Mustache.js

var template = '{{#models}}' +
               '<li class="scheduled_checkin">' +
                   '<a data-id="{{attributes.scheduleId}}" href="#/checkin/" title="Delete: {{attributes.description}}">{{attributes.title}}</a>' +
               '</li>' +
               '{{/models}}';
$('#scheduled_checkins .two-columns').html(Mustache.render(template, this.checkinsCollections));

Upvotes: 1

Related Questions