I am re-working some tooltip functionality on my site.
Am experimenting with the Revealing module pattern as laid out here:
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript
As a quick test i tried this:
var tooltip = function(){
var foobar = 'foo and bar';
function getAlerter(){
return alert(foobar);
}
return{
alerter: getAlerter
}
}();
tooltip.alerter();
Which alerts ‘foo and bar’ as expected.
However, i need to pass the element that triggered the tooltip functionality like so:
var tooltip = function(elem){
var trigger = elem;
function getAlerter(){
return alert(trigger);
}
return{
alerter: getAlerter
}
}();
tooltip.alerter('.trigger');
But this returns undefined. Am not sure why 🙁
It’s because you are using immediately executing function (
()at the end of your ‘module’), and at the moment when your function is declared and executed no value is passed.You could tell your
getAlerterfunction to accept additional parameter:but it questions the whole idea behind your pattern.
If you want to invoke your module with an element assigned, you most likely should end up with something like this:
or, if you want multiple instances, remove the
()at the end of your ‘module’, and run it like this:if you want to keep it as a single instance, you could easily add
initmethod:and run it like this: