If you look for how to pass a function as a parameter in javascript you will find solutions like this:
bar(function(){ foo("Hello World!") });
This week I learned how to use bind which I found more readable than the method above.
The bind structure is:
function.bind(thisArg,arg1,arg2,...)
thisArg – set the value of “this” to an specific object. This becomes very helpful as sometimes this is not what is intended.
arg1, arg2 – a list of values whose elements are used as the first arguments to any call to the wrapped function.
So, in this assertFirst I call a function passing another function as a parameter.
assertFirst: function() {
return this.assertion(consumer.assertThatConsumerIsValid);
}
And after assertSecond I call a function and pass a function with bind parameters, ignoring the context.
assertSecond: function(element) {
return this.assertion(consumer.assertThatConsumerIsDisplayed.bind(null,
element));
}
Then I receive the function as a parameter and call it inside this assertion.
assertion: function(assert) {
var consumers = browser.model.getConsumers();
var promises = [];
for (var i = 0; i < consumers.length; i++) {
browser.navigation.goToDetailsConsumer(i);
promises.push(assert());
}
return Q.all(promises);
}
Basically I am calling this assertion function to go to each consumer page and assert that is valid and has an element for each of them.