Is it possible to unit-test this javascript structure? - javascript

Given the following JavaScript structure:
addClickEvent: function() {
element.addEventListener('click', function() {
self.a();
self.b();
});
},
Is it possible to assert that a() and b() have been called without refactoring out the anonymous function or editing it's contents?

Assuming the self in your code is the window.self property.
You could do something like this:
function element_onclick_callsAandB() {
// Arrange
var aCalled = false;
var bCalled = false;
var element = ...;
var origA = self.a;
var origB = self.b;
self.a = function() {
aCalled = true;
origA();
};
self.b = function() {
bCalled = true;
origB();
};
try {
// Act
element.click();
// Assert
assertTrue(aCalled);
assertTrue(bCalled);
}
finally {
self.a = origA;
self.b = origB;
}
}

Related

How to overwrite event listener within prototype?

I'm trying to implement two methods: start and stop. The problem is, stop doesn't seem to work.
const MyObj = function(x) {
this.x = x;
};
MyObj.prototype.start = function(el) {
el.onclick = (function() {
console.log(this.x);
}).bind(this);
};
MyObj.prototype.stop = function(el) {
el.onclick = null;
};
const obj = new MyObj("x");
document.getElementById("checkbox").onchange = function() {
if (this.value) {
obj.start(document.body);
}
else {
obj.stop(document.body);
}
};
I've tried "" and function(){} instead null, but those were not effective either. If I set the onclick event in the browser console, after I called start, it works.
How can I fix it?
obj.stop(document.body) is never run because this.value is always true. What you're looking for is this.checked.
Fixed code :
const MyObj = function(x) {
this.x = x;
};
MyObj.prototype.start = function(el) {
el.onclick = (function() {
console.log(this.x);
}).bind(this);
};
MyObj.prototype.stop = function(el) {
el.onclick = null;
};
const obj = new MyObj("x");
document.getElementById("checkbox").onchange = function() {
if (this.checked) {
obj.start(document.body);
} else {
obj.stop(document.body);
}
};
See also this Fiddle for a demo.
Use addEventListener and removeEventListener.
el.addEventListener("click", someHandler);
// later...
el.removeEventListener('click', someHandler);
Note that someHandler must be the same object, both times. Don't use an inline function.
I've made my own version of an event handler:
var EventHandler = function(){}
EventHandler.prototype.events = [];
EventHandler.prototype.functions = [];
EventHandler.prototype.addEventListener = function(e,f,obj) // start
{
if (obj === undefined) obj = window;
this.events.push(e);
this.functions.push(f);
obj.addEventListener(e,f);
};
EventHandler.prototype.removeEventListener = function(e,obj) // stop
{
if (obj === undefined) obj = window;
var i = this.events.indexOf(event);
if (i === -1)
{
return;
}
obj.removeEventListener(event,this.functions[i]);
this.events.splice(i,1);
this.functions.splice(i,1);
//this.removeEventListener(e,obj); // to remove multiple events of the same type
}
The problem you have is that only when it runs the start method does it actually add the onclick listener.
const MyObj = function(x) {
this.x = x;
};
MyObj.prototype.start = function(el)
{
var self = this;
el.addEventListener("click",function()
{
console.log(self.x);
});
console.log("started");
console.log(el);
};
MyObj.prototype.stop = function(el) {
var self = this;
el.removeEventListener("click",function()
{
console.log(self.x);
});
console.log("stopped");
};
var test = new MyObj(54);
test.start(document.getElementById("thing"));

jquery object - function undefined error

In the following function, my objects inside floatShareBar function is undefined. Do I have to init or define a var before the functions? it throws me js error : .float - function undefined.
(function($) {
.
.
.
$("body").on("ab.snap", function(event) {
if (event.snapPoint >= 768) {
floatShareBar.float()
} else {
floatShareBar.unfloat();
}
});
var floatShareBar = function() {
var fShareBar = $('#article-share');
this.float = function() {
console.log(
};
this.unfloat = function() {
console.log("unfloat");
};
};
.
.
.
})(jQuery);
You need to get an instance of that function with a self instantiating call:
var floatShareBar = (function() {
var fShareBar = $('#article-share');
this.float = function() {
console.log('float');
};
this.unfloat = function() {
console.log("unfloat");
};
return this;
})();
UPDATE 1: I modified it to create an object within the function to attach those functions to, since in the previous example this refers to the window object
var floatShareBar = (function() {
var fShareBar = $('#article-share');
var instance = {};
instance.float = function() {
console.log('float');
};
instance.unfloat = function() {
console.log("unfloat");
};
return instance;
})();
UPDATE 2: You can actually just use the new keyword as well, look here for more info
var floatShareBar = new (function() {
var fShareBar = $('#article-share');
this.float = function() {
console.log('float');
};
this.unfloat = function() {
console.log("unfloat");
};
})();
Change you function to this:
$("body").on("ab.snap", function(event) {
if (event.snapPoint >= 768) {
(new floatShareBar()).float()
} else {
(new floatShareBar()).unfloat();
}
});
function floatShareBar () {
var fShareBar = $('#article-share');
this.float = function() {
console.log(
};
this.unfloat = function() {
console.log("unfloat");
};
};
you should declare functions when using var before you call them.

Extend prototype with another prototype

How can I extend prototype A with prototype B, so whenever I call prototype A, both will be executed?
var Helper = function() {
}
Helper.prototype.resizer = function() {
$('body').append(' Window resized ');
}
var Something = function() {
// Extend Helper.resizer with Something.anything
// extend(Helper.resizer, this.anything);
}
Something.prototype.anything = function() {
$('body').append(' Run this on resize to ');
}
var help = new Helper();
var some = new Something();
$(window).on("resize", function(){
help.resizer();
});
Made an example at codepen:
http://codepen.io/robbue/pen/892c8f61e1b5a970d6f694a59db401a6
jQuery allowed, or just vanilla.
I don't really understand your question because prototypes are not executed, but I think you want something like this:
var Helper = function() {}
Helper.prototype.resizer = function() {
$('body').append(' Window resized ');
}
var Something = function(h) {
var oldresizer = h.resizer,
that = this;
h.resizer = function() {
var res = oldresizer.apply(this, arguments);
that.anything();
return res;
};
}
Something.prototype.anything = function() {
$('body').append(' Run this on resize to ');
}
var help = new Helper();
new Something(help);
$(window).on("resize", function(){
help.resizer();
});
or that:
function Helper() {}
Helper.prototype.resizer = function() {
$('body').append(' Window resized ');
}
function Something() { // inherits Helper
Helper.apply(this, arguments);
}
Something.prototype = Object.create(Helper.prototype);
Something.prototype.anything = function() {
$('body').append(' Run this on resize to ');
};
Something.prototype.resizer = function() {
Helper.prototype.resizer.call(this);
this.anything();
};
var help = new Something(help);
$(window).on("resize", function(){
help.resizer();
});

How do I call a Javascript function outside of another Javascript function?

I have a javascript function that's supposed to toggle an animation when clicked by calling another function outside of it.
function MyFunction(id) {
var target = document.getElementById(id);
var on = true;
this.startMe = function() {
//animation code
on = true;
}
this.stopMe = function() {
//animation code
on = false;
}
this.toggleMe = function() {
if (on) this.stopMe();
else this.startMe();
}
target.addEventListener('click', function() {
this.toggleMe();
}, false);
}
The problem lies in the toggleMe and addEventListener functions. "this" refers to the function itself and not the one containing it, which is what I need it to reference. How can I work around this?
The easy fix is to use a closure variable as given below
function MyFunction(id) {
var self = this;
var target = document.getElementById(id);
var on = true;
this.startMe = function () {
//animation code
on = true;
}
this.stopMe = function () {
/animation code
on = false;
}
this.toggleMe = function() {
if (on) this.stopMe();
else this.startMe();
}
target.addEventListener('click', function() {
//this refers to the element here not the instance of MyFunction
//use a closure variable
self.toggleMe();
}, false);
}
Another solution is to pass a custom execution context to the callback using $.proxy() - you can use Function.bind() also but not supported in IE < 9
function MyFunction(id) {
var target = document.getElementById(id);
var on = true;
this.startMe = function () {
//animation code
on = true;
}
this.stopMe = function () {
//animation code
on = false;
}
this.toggleMe = function () {
if (on) this.stopMe();
else this.startMe();
}
//use Function.bind() to pass a custom execution context to
target.addEventListener('click', jQuery.proxy(function () {
// this refers to the element here not the instance of MyFunction
//use a closure variable
this.toggleMe();
}, this), false);
}
Also use .click()/on('click') to register the click handler instead of addEventListener
$(target).on('click', jQuery.proxy(function () {
// this refers to the element here not the instance of MyFunction
//use a closure variable
this.toggleMe();
}, this), false);
Simply add another variable with a reference to this but with a different name; then you can use that in your functions.
function MyFunction(id) {
var self = this;
var target = document.getElementById(id);
var on = true;
this.startMe = function() {
on = true;
}
this.stopMe = function() {
on = false;
}
this.toggleMe = function() {
if (on) self.stopMe();
else self.startMe();
}
target.addEventListener('click', function() {
self.toggleMe();
}, false);
}
My personal preference is to take it even one step further and continue to use self everywhere that makes sense:
function MyFunction(id) {
var self = this;
var target = document.getElementById(id);
var on = true;
self.startMe = function() {
on = true;
}
self.stopMe = function() {
on = false;
}
self.toggleMe = function() {
if (on) self.stopMe();
else self.startMe();
}
target.addEventListener('click', function() {
self.toggleMe();
}, false);
}

Accessing a function within a function from outside in javascript

I have a nested function that I want to call from outside.
var _Config = "";
var tourvar;
function runtour() {
if (_Config.length != 0) {
tourvar = $(function () {
var config = _Config,
autoplay = false,
showtime,
step = 0,
total_steps = config.length;
showControls();
$('#activatetour').live('click', startTour);
function startTour() {
}
function showTooltip() {
}
});
}
}
function proceed() {
tourvar.showTooltip();
}
$(document).ready(function () {
runtour();
});
I was hoping to call it by tourvar.showTooltip(); but I seem to be wrong :) How can I make showTooltip() available from outside the function?
since my previous answer was really a hot headed one, I decided to delete it and provide you with another one:
var _Config = "";
var tourvar;
// Module pattern
(function() {
// private variables
var _config, autoplay, showtime, step, total_steps;
var startTour = function() { };
var showTooltip = function() { };
// Tour object constructor
function Tour(config) {
_config = config;
autoplay = false;
step = 0;
total_steps = _config.length;
// Provide the user with the object methods
this.startTour = startTour;
this.showTooltip = showTooltip;
}
// now you create your tour
if (_Config.length != 0) {
tourvar = new Tour(_Config);
}
})();
function proceed() {
tourvar.showTooltip();
}
$(document).ready(function () {
runtour();
});
function outerFunction() {
window.mynestedfunction = function() {
}
}
mynestedfunction();

Categories

Resources