当前位置:  开发笔记 > 编程语言 > 正文

链式承诺和原型`this`

如何解决《链式承诺和原型`this`》经验,为你挑选了0个好方法。

我很难获得承诺this在原型中使用正确的范围.

这是我的代码:

'use strict';

angular.module('testApp').factory('UrlSearchApi',
  function($resource, URL_SEARCH_API, PAGE_SIZE, $q){

  var resource = $resource(URL_SEARCH_API);

  resource.Scroll = function () {
    return this.reset();
  };

  resource.Scroll.prototype.reset = function () {
    this.visibleItems = [];
    this.allItems = [];
    this.busy = null;
    return this;
  };

  resource.Scroll.prototype.fetch = function(query){
    var params = {};
    if(query) { params.q = query; }
    return resource.query(params).$promise;
  };

  resource.Scroll.prototype.loadAllItems = function (results) {
    var d = $q.defer();

    angular.forEach(results, function (result, i) {
      this.allItems.push(result);
      if(i === results.length - 1 ) { d.resolve(); }
    }, this);

    return d.promise;
  };

  resource.Scroll.prototype.loadVisibleItems = function () {
    var length = this.visibleItems.length,
        offset = parseInt(length / PAGE_SIZE),
        start = PAGE_SIZE * offset,
        end = start + PAGE_SIZE,
        subset = this.allItems.slice(start, end),
        d = $q.defer();

    angular.forEach(subset, function (item, i) {
      this.visibleItems.push(item);
      if(i === subset.length - 1 ) { d.resolve(); }
    }, this);

    return d.promise;
  };

  resource.Scroll.prototype.nextPage = function (query) {
    if(this.busy) { return; }

    console.log('nextPage ', query);
    var tasks = [],
        that = this;

    if(!this.allItems.length) {
      this.reset();
      this.busy = true;
      return this.fetch(query)
        .then(this.loadAllItems)
        .then(this.loadVisibleItems)
        .finally(function () {
          this.busy = false;
        });
    } else {
      this.busy = true;
      return this.loadVisibleItems().finally(function () {
        this.busy = false;
      });
    }
  };

  return resource;
});

每当我运行测试时,我都会得到

describe('#nextPage', function () {
  var scroll;

  describe('when there is NO search term (show all)', function () {

    beforeEach(function (done) {
      scroll = new UrlSearchApi.Scroll();

      $httpBackend.expectGET('/policy/search')
        .respond(200, arrayGenerator(123));
      scroll.nextPage().then(done);
      $httpBackend.flush();
      $rootScope.$apply();
    });

    it('should load all the items in all items variable', function () {
      expect(scroll.allItems.length).toBe(123);
    });
 });

});

我收到以下错误:

TypeError: 'undefined' is not an object (evaluating 'this.allItems')

我现在$q在严格模式下将this内部设置thenundefined.我试过bind(this)在多个地方使用但没有运气......有什么想法吗?

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有