如何在Backbone fetch到另一个fetch之后添加响应中的元素

时间:2015-05-20 05:39:22

标签: javascript backbone.js handlebars.js

 var ChannelStatsView = Backbone.View.extend({
  el: "#id-channel-stats",
  initialize: function() {

    var _this = this;

    this.modelChannelList = new channelListModel();
    this.modelChannelStats = new channelStatsModel();
    this.channelstatsCollection = new channelStatsCollection();

    this.channelNames = [];
    this.listOfObjects = [];

    this.modelChannelList.fetch({
      success: function(model, response, options) {
        model.set();
        _this.formatChannelIds();

      },

      error: function(model, xhr, options) {

      }
    });
  },
  formatChannelIds: function() {

    _this = this;
    _.filter(_this.modelChannelList.toJSON(), function(channelObj) {
      if (channelObj['isactive'] == true) {
        _this.updateStats(channelObj['id'], channelObj['name']);
      }
    });
  },

  updateStats: function(id, name) {

    var _this = this;

    _this.modelChannelStats.fetch({
      data: {
        channel: id
      },
      processData: true,
      success: function(model, response, options) {

        _this.response = response;
        _this.listOfObjects.push(_this.response.records[0]);
        _this.channelNames.push(name);
      }
    }).done(function(model, response, options) {
      _this.render();
    });
  },
  render: function() {

    var _this = this;

    if (_this.listOfObjects.length == 0) {

    } else {
      _this.template = channelTemplate;
      _this.$el.html(_this.template({
        orderData: _this.listOfObjects,
        channelNames: _this.channelNames
      }));
    }
  }
});

在我的代码中,我从一个model.fetch查询中获取响应,即this.modelChannelList并获取所有活动ID然后将其提供给另一个fetch以获得响应我知道这个解决方案非常糟糕可以有人帮助我如何使其更快更有效。

我正在考虑使用Promises

1 个答案:

答案 0 :(得分:0)

您需要处理的主要问题是您正在进行的获取请求的数量。承诺很酷,所以我也包括在内。以下是我建议你做的事情:

1)更新您的模型类,将获取函数指定为延迟

var channelListModel = Backbone.Model.extend({
    initialize: function() {
        // Assign the Deferred issued by fetch() as a property
        this.deferred = this.fetch();
    }
});

2)修改您的updateStats / formatChannels逻辑以创建一个ID数组,并通过您的提取传递这些逻辑以获取完整的数据集。这将通过减少您必须拨打的电话数来节省大量时间

initialize: function() {
    // other stuff here...
    this.modelChannelList.deferred.done(function(model) {
        model.set();
        view.formatChannelIds();
    });
    // other stuff here...
}

formatChannelIds: function() {
    var _this = this,
        ids = [];

    _.filter(_this.modelChannelList.toJSON(), function(channelObj) {
        if (channelObj['isactive'] == true) {
            ids.push(channelObj['id']);
        }
        _this.updateStats(ids);
    });
}

您必须稍微改变您的数据服务,但这是最终必要的更改。