【问题标题】:jQuery DOM event not working on Backbone ViewjQuery DOM 事件在主干视图上不起作用
【发布时间】:2023-04-02 10:45:01
【问题描述】:

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

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. 点击签入(当前查看代码)
  3. 回家
  4. 视图呈现,但将项目添加到列表中

图片

我第一次加载视图

假设我转到另一个视图,现在我回到这个视图

又一次:(

【问题讨论】:

  • 可以加个jsfiddle/jsbin吗?
  • 顺便说一句,`$('li.scheduled_checkin').remove()` 可能也会起作用,因为它具有隐式迭代,如 here
  • @alonisser 我试过了,但不起作用,这是 jsfiddle jsfiddle.net/rommelxcastro/Pnwp8
  • 抱歉,小提琴不好,因为您不提供任何 html。我猜你要么在类名中有错字,所以each 函数没有运行。或者没有调用该渲染
  • @alonisser 如果你看到第 43 行,你可以看到我在哪里创建 html ;)

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


【解决方案1】:

从你的 jsfiddle 没有工作的 HTML 示例,在这个函数:

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

【讨论】:

  • 我几分钟前才找到这个解决方案,我想回答这个问题,我看到了你的回复,是的,这解决了问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多