Reuse of functions - javascript

I think I know the theory behind the solution but I am having trouble implementing it. Consider following piece of code:
this.selectFirstPassiveService = function () {
getFirstPassiveService().element(by.tagName('input')).click();
}
this.clickAddTask = function () {
getFirstActiveService().element(by.tagName('a')).click();
}
this.selectTask = function () {
getFirstActiveService()
.element(by.tagName('option'))
.$('[value="0"]')
.click();
}
this.saveTask = function () {
getFirstActiveService().element(by.name('taskForm')).submit();
}
getFirstActiveService = function () {
return services.filter(function (elem) {
return elem.getAttribute('class').then(function (attribute) {
return attribute === 'service active ';
});
}).first();
}
getFirstPassiveService = function () {
return services.filter(function (elem) {
return elem.getAttribute('class').then(function (attribute) {
return attribute === 'service passive ';
});
}).first();
}
};
To minimalize code duplication, I created two functions:
* getFirstActiveService()
* getFirstPassiveService()
My spec goes as follows:
it('Select service', function () {
servicePage.selectFirstPassiveService();
servicePage.clickAddTask();
servicenPage.selectTask()();
});
Both clickAddTask() and selectTask() use the function called getFirstActiveService(). Everything runs fine in clickAddTask() but when I use the function in selectTask(), some elements (which are present) cannot be found by protractor.
Here goes my theory, every command in getFirstActiveService() is queued in the control flow when the function is called in clickAddTask() and is then executed. When reusing the function in selectTask() the commands aren't queued, the instance created in clickAddTask() is used and therefore, some elements cannot be found since the DOM has changed since then.
Now first question: Is my theory correct?
Second question: How can I fix this?
Thanks in advance!
Cheers

I refactored it a bit and it works now.
The problem was in the test itself, not in the reuse of functions.

Related

Passing argument to the function inside the object in Javascript

I'm quite sure this question has been asked before, but I couldn't find anything related to my case.
Here's my function
function change(prop) {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
spacing.onchange = change;
blur.onchange = change;
I'm struggling with passing argument to change function, because if I do spacing.onchange = change("prop") the function will be executed immediately. I want to avoid using addEventListener. So here's the question, how can I pass an argument to my function?
You can solve that by using high order function feature
function change(prop) {
return function() {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
}
// for example
spacing.onchange = change(/*Your prop*/);
blur.onchange = change(/*Your prop*/);
spacing.onchange = change.bind(spacing, 'prop');
Try setting the variable equal to the function definition.
spacing.onchange = function change(prop) {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
spacing.onchange(arg);
Try this:
function onChanges (variables,props) {
variables.forEach((variable, index) => {
variable.onChange=function(event){
return change(props[index]);
}
});
}
onChanges([spacing,blur],[prop1,prop2]);

Getting correct scope in functions (not using that = this)

I am trying to fix a function I have here to be able to use it without using a that = this (or self = this as some like to use). It is a scoping issue but I am not sure how to get around it, and I would like to get in the habit of not using a that = this . So the functions are all in a return (angular factory) and I am having trouble referencing another function . Let me show you what I mean :
return {
loadStates: function() {
var that = this;
//chgeck if is loaded module, then change and fire callback
var currentModules = moduleHolder.getModules();
if (currentModules[name]) {
//works here
this.prepState();
} else {
//module cannot be found check for 5 seconds
$log.warn("Requesting " + name + "...");
var timeToCheck = true;
setTimeout(function() {
timeToCheck = false;
}, 5000);
var check = {
init: function() {
check.checkAgain();
},
checkAgain: function() {
if (timeToCheck) {
if (currentModules[name]) {
//but not here
that.prepState();
} else {
//still doesn't exists
setTimeout(check.checkAgain, 200);
}
} else {
//doesn't exist after 5 seconds
$log.error("Requested module (" + name + ") could not be found at this time.");
}
}
};
check.init();
}
},
prepState: function() {
}
}
So in the top if it finds the currentModule[name] I can use a this.prepState() and it works fine. However inside the timing functions I cannot use the this anything because it is inside a different scope so I have temporarily gotten around this by setting a that = this up top, however I would like see if I could not use this method. How does one get around this without using the that= this? Thanks!
It is a scoping issue...
No, it isn't. this and scope have essentially nothing to do with each other. (For now; ES6's arrow functions will change that.) It's an issue of how the functions are called.
If you pass a function reference to something that will call it later, unless the thing you're passing it to has a way you can use to tell it what to use for this when calling it, your function will get called with this not referring to what you want it to refer to.
You can get a new function reference that will call your original function with the correct this by using Function#bind:
var usesCorrectThis = originalFunction.bind(valueForThis);
So for example, suppose I have:
var check = {
name: "Fred",
sayHello: function() {
console.log("Hi, I'm " + this.name);
}
};
If I do:
check.sayHello();
All is good: Calling the function as part of an expression retrieving it from a property tells the JavaScript engine to use the object as this during the call.
However, if I do:
setTimeout(check.sayHello, 0);
...that doesn't work right, because when setTimeout calls the function, it doesn't use the right value for this.
So I can use Function#bind to address that:
setTimeout(check.sayHello.bind(check), 0);
More (on my blog):
Mythical methods
You must remember this
there are different ways you can do that.
One way is to use bind function.you can use
var checkInitBindFn = check.init.bind(this);
checkInitBindFn();
Secondly you can use call and apply also.
check.init.call(this);
check.init.apply(this);
Like this you can use this instead of that.
Check the complete api doc online...
It's not a scoping issue. If you want to avoid self = this you can always reference functions by objects. Makes cleaner code and since factories in angular are singletons you're not wasting memory.
angular.module('myApp').factory('myFactory', function ($timeout) {
var myFactory = {
loadState: function () {
$timeout(function () {
myFactory.check();
}, 500);
},
check: function () {
},
};
return myFactory;
});

Array value as condition of if else- JS

I've been trying to understand why whenever value of the array I click, it always add the class "foo".
Example: I clicked on London (cities[1], right?) and it added the class foo.
var cities = [
document.getElementById('Paris'),
document.getElementById('London'),
document.getElementById('Berlin')
];
for (var i = 0; i < cities.length; i++) {
cities[i].onclick = test;
function test(){
if(cities[i] === cities[0]) {
el.classList.add("foo");
}
}
}
EDIT: my original answer was incorrect, this updated one is right. addEventListener returns nothing. Instead, you should use some kind of wrapper to add and remove your listeners, again so that you don't waste resources on listeners that you aren't using:
function on (element, eventName, callback) {
element.addEventListener(eventName, callback);
return function unregister () {
element.removeEventListener(callback);
}
}
function test (event) {
if (event.currentTarget===cities[0]) {
event.target.classList.add('foo');
}
}
var listenerRemovers = cities.map(function (city) {
return on(city, 'click', test);
});
Now you can remove any of these listeners by calling the corresponding function in your listenerRemovers array:
listenerRemovers.forEach(function (unRegisterFunc) { unRegisterFunc(); });
ORIGINAL WRONG ANSWER:
For what it's worth, you're probably better off using .map in a case like this, since best practice is to keep a reference to the event listeners so you can cancel them if needed.
function test (event) {
if (event.currentTarget===cities[0]) {
event.target.classList.add('foo');
}
}
var listenerHandlers = cities.map(function (city) {
return city.addEventListener('click', test);
});
This is happening because you are setting the event functions inside a loop. Each function is using the same value of i.
Try to use this instead of trying to cities[i] inside the function.
function test(){
if(this === cities[0]) {
el.classList.add("foo");
}
}
The easiest approach to achieve this functionality is to use jQuery, here is the idea:
In html tags, give those cities a common class, e.g. class="city"
$('.city').click(function(){$('.city').addClass('foo')});
jQuery saves you more time and coding efforts.
The problem is you are trying to assign a function to a DOM attribute. You are not registering a listener but modifying the DOM. If you wish to do it this way, you must assign the onclick as cities[i].onclick = 'test()'
Also, you should move the function test outside of the for loop to look like the following. The problem is the function test is being declared many times, each with a different 'i' value.
for (var i = 0; i < cities.length; i++) {
cities[i].onclick = 'test(this)';
}
function test(el){
if(cities[i] === cities[0]) {
el.classList.add("foo");
}
}

Passing collection.fetch as a named function to collection.bind does not work

I have two Backbone collections. I want to bind to the reset event one one. When that event is fired, I want to call fetch on the second collection, like so:
App.collections.movies.bind("reset", App.collections.theaters.fetch);
The second fetch never fires though. However, if I pass an anonymous function that calls theaters.fetch, it works no problem:
App.collections.movies.bind("reset", function () { App.collections.theaters.fetch(); });
Any idea why this might be the case?
Heres my full code. I'm not showing any of the models or collections, because it's a lot of code, but let me know if you think that might be the source of the problem:
var App = {
init: function () {
App.collections.theaters = new App.Theaters();
App.collections.movies = new App.Movies();
App.events.bind();
App.events.fetch();
},
events: {
bind: function () {
App.collections.theaters.bind("reset", App.theaterManager.assign);
App.collections.movies.bind("reset", function () { App.collections.theaters.fetch(); });
},
fetch: function () {
App.collections.movies.fetch();
}
},
collections: {},
views: {},
theaterManager: {
// Provide each model that requires theaters with the right data
assign: function () {
// Get all theaters associated with each theater
App.theaterManager.addToCollection("theaters");
// Get all theaters associated with each movie
App.theaterManager.addToCollection("movies");
},
// Add theaters to a collection
addToCollection: function (collection) {
App.collections[collection].each(function (item) {
item.theaters = App.theaterManager.getTheaters(item.get(("theaters")));
});
},
// Returns a collection of Theaters models based on a list of ids
getTheaters: function () {
var args;
if (!arguments) {
return [];
}
if (_.isArray(arguments[0])) {
args = arguments[0];
} else {
args = Array.prototype.slice.call(arguments);
}
return new App.Theaters(_.map(args, function (id) {
return App.collections.theaters.get(id);
}));
}
}
};
$(function () {
App.init();
});
This all has to do with function context. It is a common confusion with the way functions are called in Javascript.
In your first way, you are handing a function to be called, but there is no context defined. This means that whoever calls it will become "this". It is likely that the equivalent will be of calling App.collections.movies.fetch() which is not what you want. At least, I am guessing that is what the context will be. It is difficult to know for sure... it might be jQuery, it might be Backbone.sync. The only way to tell is by putting a breakpoint in the Backbone.collections.fetch function and print out the this variable. Whatever the case, it won't be what you want it to be.
In the second case, you hand it a function again but internally, you specify the context in which the function is called. In this case, fetch gets called with App.collections.theaters as the context.
... was that clear?

Javascript function hooks

EDIT: OK, I believe the following solutions are valid:
Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
I've been trying to hack something up for a couple of hours, but so far no luck.
Might not be pretty but it seems to work...
<script>
function A(x) { alert(x); return x; }
function B() { alert(123); }
function addHook(functionB, functionA, parent)
{
if (typeof parent == 'undefined')
parent = window;
for (var i in parent)
{
if (parent[i] === functionA)
{
parent[i] = function()
{
functionB();
return functionA.apply(this, arguments)
}
break;
}
}
}
addHook(B, A);
A(2);
</script>
Take a look at jQuery's AOP plugin. In general, google "javascript aspect oriented programming".
Very simple answer:
function someFunction() { alert("Bar!") }
var placeholder=someFunction;
someFunction=function() {
alert("Foo?");
placeholder();
}
This answer is not definitive, but rather demonstrative of a different technique than those offered thus far. This leverages the fact that a function in Javascript is a first-class object, and as such, a) you can pass it as a value to another function and b) you can add properties to it. Combine these traits with function's built-in "call" (or "apply") methods, and you have yourself a start toward a solution.
var function_itself = function() {
alert('in function itself');
}
function_itself.PRE_PROCESS = function() {
alert('in pre_process');
}
function_itself.POST_PROCESS = function() {
alert('in post_process');
}
var function_processor = function(func) {
if (func.PRE_PROCESS) {
func.PRE_PROCESS.call();
}
func.call();
if (func.POST_PROCESS) {
func.POST_PROCESS.call();
}
}
The following function will give you before and after hooks that can be stacked. So if you have a number of potential functions that need to run before the given function or after the given function then this would be a working solution. This solution does not require jQuery and uses native array methods (no shims required). It should also be context sensitive so if you are calling the original function with a context if should run each before and after function likewise.
// usage:
/*
function test(x) {
alert(x);
}
var htest = hookable(test);
htest.addHook("before", function (x) {
alert("Before " + x);
})
htest.addHook("after", function (x) {
alert("After " + x);
})
htest("test") // => Before test ... test ... After test
*/
function hookable(fn) {
var ifn = fn,
hooks = {
before : [],
after : []
};
function hookableFunction() {
var args = [].slice.call(arguments, 0),
i = 0,
fn;
for (i = 0; !!hooks.before[i]; i += 1) {
fn = hooks.before[i];
fn.apply(this, args);
}
ifn.apply(this, arguments);
for (i = 0; !!hooks.after[i]; i++) {
fn = hooks.after[i];
fn.apply(this, args);
}
}
hookableFunction.addHook = function (type, fn) {
if (hooks[type] instanceof Array) {
hooks[type].push(fn);
} else {
throw (function () {
var e = new Error("Invalid hook type");
e.expected = Object.keys(hooks);
e.got = type;
return e;
}());
}
};
return hookableFunction;
}
Here's what I did, might be useful in other applications like this:
//Setup a hooking object
a={
hook:function(name,f){
aion.hooks[name]=f;
}
}a.hooks={
//default hooks (also sets the object)
};
//Add a hook
a.hook('test',function(){
alert('test');
});
//Apply each Hook (can be done with for)
$.each(a.hooks,function(index,f){
f();
});
I don't know if this will be useful. You do need to modify the original function but only once and you don't need to keep editing it for firing hooks
https://github.com/rcorp/hooker

Categories

Resources