chore(core): create a wrapper to manage async callbacks

This commit is contained in:
Matias Niemelä
2014-02-24 19:21:20 -05:00
parent 04d7317cdd
commit 62761428ef
5 changed files with 63 additions and 2 deletions

1
angularFiles.js vendored
View File

@@ -11,6 +11,7 @@ angularFiles = {
'src/ng/anchorScroll.js',
'src/ng/animate.js',
'src/ng/asyncCallback.js',
'src/ng/browser.js',
'src/ng/cacheFactory.js',
'src/ng/compile.js',

View File

@@ -73,7 +73,7 @@
$TemplateCacheProvider,
$TimeoutProvider,
$$RAFProvider,
$AsyncCallbackProvider,
$$AsyncCallbackProvider,
$WindowProvider
*/
@@ -214,7 +214,8 @@ function publishExternalAPI(angular){
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$rAF: $$RAFProvider
$$rAF: $$RAFProvider,
$$asyncCallback : $$AsyncCallbackProvider
});
}
]);

11
src/ng/asyncCallback.js Normal file
View File

@@ -0,0 +1,11 @@
'use strict';
function $$AsyncCallbackProvider(){
this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
return $$rAF.supported
? function(fn) { return $$rAF(fn); }
: function(fn) {
return $timeout(fn, 0, false);
};
}];
}

View File

@@ -1684,6 +1684,20 @@ angular.mock.$RAFDecorator = function($delegate) {
return rafFn;
};
angular.mock.$AsyncCallbackDecorator = function($delegate) {
var callbacks = [];
var addFn = function(fn) {
callbacks.push(fn);
};
addFn.flush = function() {
angular.forEach(callbacks, function(fn) {
fn();
});
callbacks = [];
};
return addFn;
};
/**
*
*/
@@ -1718,6 +1732,7 @@ angular.module('ngMock', ['ng']).provider({
}).config(['$provide', function($provide) {
$provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
$provide.decorator('$$rAF', angular.mock.$RAFDecorator);
$provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator);
}]);
/**

View File

@@ -0,0 +1,33 @@
'use strict';
describe('$$asyncCallback', function() {
it('should perform a callback asynchronously', inject(function($$asyncCallback) {
var message = 'hello there ';
$$asyncCallback(function() {
message += 'Angular';
});
expect(message).toBe('hello there ');
$$asyncCallback.flush();
expect(message).toBe('hello there Angular');
}));
describe('mocks', function() {
it('should queue up all async callbacks', inject(function($$asyncCallback) {
var callback = jasmine.createSpy('callback');
$$asyncCallback(callback);
$$asyncCallback(callback);
$$asyncCallback(callback);
expect(callback.callCount).toBe(0);
$$asyncCallback.flush();
expect(callback.callCount).toBe(3);
$$asyncCallback(callback);
$$asyncCallback(callback);
expect(callback.callCount).toBe(3);
$$asyncCallback.flush();
expect(callback.callCount).toBe(5);
}));
});
});