在 Backbone.js 集合中填充来自两个不同URL的数据

sigwle7e  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(132)

我有一个Marionette.LayoutView,它调用一个 Backbone.js 集合,获取数据,并根据响应进行渲染。现在我面临的问题是,这个集合需要从两个不同的端点获取数据,这两个端点应该是独立的,然后返回组合的结果。下面是我的代码:
我的Marionette.LayoutView

var View = Marionette.LayoutView.extend({

    template: _.template(some.html),

    regions: {
        div1: '[data-region="div1"]',
        div2: '[data-region="div2"]',
    },

    initialize: function () {
        this.collection = new MovieCollection();
    },

    onRender: function () {
        if (this.collection.length) {
            this.div1.show(new TopMoviesByLikesView({
                collection: this.collection,
                movieCount: 10,
            }));

            this.div2.show(new TopMovieByRatingsView({
                collection: this.collection,
                movieCount: 10,
            }));
        }
    },

});

module.exports = AsyncView.extend({
    ViewConstructor: View,
});

我的Collection

module.exports = Backbone.Collection.extend({

    model: TopMovieModel,

    initialize: function (response) {
        let movieCollection = [];
            let movieSourceOne = new TopMovieFromSourceOne();
            movieSourceOne.fetch({
                success: function (collection, response) {
                    movieCollection = [...movieCollection, ...response.data];
                },
                error: function (collection, response, options) {
                    console.info('~ Response::ERROR', collection, response, options);
                }
            });
        let movieSourceTwo = new movieSourceTwo();
        movieSourceTwo.fetch({
            success: function (collection, response, options) {
                movieCollection = [...movieCollection, ...response.data];
            },
            error: function(collection, response, options) {
                console.info('~ Response::ERROR', collection, response, options);
            }
        });
        this.collection = movieCollection;
    },

我得到的错误是A “url” property or function must be specified有没有方法可以在不使用 Backbone.js 集合中的url的情况下执行此操作?注意:我希望保持两个端点的独立性,因为我不希望在主API失败时收集失败。

7gs2gvoe

7gs2gvoe1#

若要避免url的错误,您应该覆写fetch方法,改为呼叫两个集合fetch

function promisifyFetch(collection) {
  return new Promise(function(resolve, reject) {
    collection.fetch({
      success() {
        resolve(collection);
      },

      error() {
        reject();
      }
    });
  });
}

module.exports = Backbone.Collection.extend({
  model: TopMovieModel,

  initialize() {
    this.movieSourceOne = new TopMovieFromSourceOne();
    this.movieSourceTwo = new movieSourceTwo();
  },

  fetch(options) {
    return Promise.all([
      promisifyFetch(this.movieSourceOne),
      promisifyFetch(this.movieSourceTwo)
    ]).then(([one, two]) => {
      const response = [
        ...one.toJSON(),
        ...two.toJSON()
      ];

      this.set(response, options);
      this.trigger('sync', this, response, options);
    });
  }
});

您可能也想在这里处理错误。

相关问题