Implement filter context

closes #2559
- Added a new unit test for context based filters
- Accept new parameter `context` in doFilter
This commit is contained in:
Fabian Becker 2014-04-06 15:43:11 +00:00
parent c38c778dbc
commit c2e416fc9d
2 changed files with 31 additions and 2 deletions

View File

@ -58,7 +58,7 @@ Filters.prototype.deregisterFilter = function (name, priority, fn) {
}; };
// Execute filter functions in priority order // Execute filter functions in priority order
Filters.prototype.doFilter = function (name, args) { Filters.prototype.doFilter = function (name, args, context) {
var callbacks = this.filterCallbacks[name], var callbacks = this.filterCallbacks[name],
priorityCallbacks = []; priorityCallbacks = [];
@ -71,13 +71,20 @@ Filters.prototype.doFilter = function (name, args) {
_.times(defaults.maxPriority + 1, function (priority) { _.times(defaults.maxPriority + 1, function (priority) {
// Add a function that runs its priority level callbacks in a pipeline // Add a function that runs its priority level callbacks in a pipeline
priorityCallbacks.push(function (currentArgs) { priorityCallbacks.push(function (currentArgs) {
var callables;
// Bug out if no handlers on this priority // Bug out if no handlers on this priority
if (!_.isArray(callbacks[priority])) { if (!_.isArray(callbacks[priority])) {
return when.resolve(currentArgs); return when.resolve(currentArgs);
} }
callables = _.map(callbacks[priority], function (callback) {
return function (args) {
return callback(args, context);
};
});
// Call each handler for this priority level, allowing for promises or values // Call each handler for this priority level, allowing for promises or values
return when.pipeline(callbacks[priority], currentArgs); return when.pipeline(callables, currentArgs);
}); });
}); });

View File

@ -128,4 +128,26 @@ describe("Filters", function () {
}); });
}); });
it("executes filters with a context", function (done) {
var filterName = 'textContext',
testFilterHandler1 = sinon.spy(function (args, context) {
args.context1 = _.isObject(context);
return args;
}),
testFilterHandler2 = sinon.spy(function (args, context) {
args.context2 = _.isObject(context);
return args;
});
filters.registerFilter(filterName, 0, testFilterHandler1);
filters.registerFilter(filterName, 1, testFilterHandler2);
filters.doFilter(filterName, { test: true }, { context: true }).then(function (newArgs) {
newArgs.context1.should.equal(true);
newArgs.context2.should.equal(true);
done();
});
});
}); });