jQuery DOM事件无法在Backbone View上运行

时间:2013-03-04 18:01:35

标签: jquery dom backbone.js backbone-views backbone-events

我有一个观点,每次调用时都会重新渲染视图中的元素,这里是代码片段:

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();
}

这是一个案例:

  1. 打开主页
  2. 点击checkIn(当前视图代码)
  3. 回到家里
  4. 视图呈现,但将项目添加到列表
  5. 图像

    我第一次加载视图 first time i load the view

    让我们说我转到另一个视图,现在我回到这个视图 let's say that i go to another view and now i come back to this view

    再次:( and again

1 个答案:

答案 0 :(得分:1)

从没有工作HTML示例的jsfiddle,在此函数:

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>';
}

我猜你在重新渲染视图时忘了重置this.checkinsHtml。

修改:为了更好的方式,您应该从模板中渲染html。

使用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));