Saturday, 14 September 2013

attachEvent is not a function - Using Module Pattern

attachEvent is not a function - Using Module Pattern

I am trying to build a JavaScript module to better understand the pattern.
I am trying to attach click events to a button with addEventListener and
attachEvent but I can not get my console.log to register.
I am also getting an error that says "TypeError: element.attachEvent is
not a function"
Here is a fiddle that I have at the moment: http://jsfiddle.net/rL5xp/
Here is the HTML:
<p>The color is <span class="js-print">green</span>.</p>
<button class="js-button">Click Here</button>
Here is the JavaScript:
var settings = [
{color : 'green'},
{color : 'blue'},
{color : 'red'}
];
var $ele = {
span : $('.js-print'),
button : $('.js-button')
};
var ChangeColor = (function(s, $element) {
var init = function() {
bindBrowserActions();
}
var bindBrowserActions = function() {
addClick($element.button, 'click', function() {
console.log('click');
});
}
var addClick = function(element, evnt, funct) {
if (element.addEventListener) {
return element.addEventListener(evnt, funct, false);
}
//addEventListener is not supported in <= IE8
else {
return element.attachEvent('on'+evnt, funct);
}
}
return {
init : init
}
})(settings, $ele);
(function() {
ChangeColor.init();
})();

No comments:

Post a Comment