【问题标题】:How to add spinner on index view to fetch in Backbone?如何在索引视图上添加微调器以在 Backbone 中获取?
【发布时间】:2013-02-12 23:01:16
【问题描述】:

这是我收藏的视图:

Network.Views.Offers.Index = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, 'render');
    this.collection = new Network.Collections.Offers();
    this.collection
    .on('reset', this.render)
    .fetch();
  },

  render: function() {
    var self = this;
    _.each(this.collection.models, function(model) {
      var view = new Network.Views.Offers.Offer({ model: model });
      $(self.el).append(view.el);
      view.adjustHeight();
    });
    return this;
  },
});

我尝试在成功获取后添加和删除微调器类:

this.$el.append('<div class="loading">Loading...</div>');
this.collection
.on('reset', this.render)
.fetch({
  success:function() {
    this.$el.removeClass('loading');
  }
});

但我明白了:

Uncaught TypeError: Cannot call method 'removeClass' of undefined 

【问题讨论】:

  • 可能在您的集合获取数据时添加wait:true

标签: javascript backbone.js spinner


【解决方案1】:
this.$el.append('<div class="loading">Loading...</div>');

在 $el 元素中添加一个具有加载类的 div。

this.$el.removeClass('loading');

removeClass 不会删除具有指定类的元素中的元素。

试试:

this.$el.append('<div class="loading">Loading...</div>');
var $this = this; // maintain the context of this within the success callback
this.collection
.on('reset', this.render)
.fetch({
  success:function() {
    $this.$('.loading').remove();
  }
});

【讨论】:

    【解决方案2】:

    您收到 TypeError 是因为 $el 未在 success 回调中的 this 上定义。这是因为success 回调中的this 不是指您的Index 视图。

    您需要将this 绑定到该回调,以使this 引用该回调中的Index 视图..

    success:function() {
      this.$el.removeClass('loading');
    }.bind(this)
    

    了解bind on MDN

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多