I have several Widgets (in the example below, see Button) on a page that I attach events to via a page Controller (see Controller).
Each Widget inherits from the Widget class.
Problem I have, is that when I assign an event in the Controller, it seems like both the Buttons are getting the event added to their observers array. I can't really figure out why...
P.S The code below is simplified to show the issue. Error handling etc is removed for clarity.
/José Jeria
Code:
<html>
<body>
<div id="myFirstDiv">1: click me</div>
<div id="mySecondDiv">2: click me</div>
<script>
/**
* Constructs a Widget object.
*/
function Widget()
{
this.observers = [];
}
/**
* Adds listeners to observers array.
*
* @param oListener Object that will listen to events.
*/
Widget.prototype.addListener = function(oListener)
{
this.observers.push(oListener);
}
/**
* Notifies the observers.
*
* @param oWidgetEvent Normally I pass an object with properties here, but for this example, its a String.
*/
Widget.prototype.notifyListeners = function(oWidgetEvent)
{
for(var i=0; i<this.observers.length; i++)
{
this.observers[i].actionPerformed(oWidgetEvent);
}
}
/**
* Button constructor
*
* @param sId Id of html element.
*/
function Button(sId)
{
this.button = document.getElementById(sId);
var oThis = this;
this.button.onclick = function()
{
oThis.notifyListeners("test");
}
}
/**
* Inherit from Widget Class.
*/
Button.prototype = new Widget();
/**
* Page controller constructor
*/
function Controller()
{
this.firstButton = oFirstButton;
this.secondButton = oSecondButton;
this.attachListeners();
}
/**
* Assigns events to components.
*/
Controller.prototype.attachListeners = function()
{
this.firstButton.addListener(this);
this.secondButton.addListener(this);
}
/**
* What action to perform when a specific component fires an event.
*
* @param sWhatever Hardcoded string from the Button class.
*/
Controller.prototype.actionPerformed = function(sWhatever)
{
alert(sWhatever);
}
// Create instances
var oFirstButton = new Button("myFirstDiv");
var oSecondButton = new Button("mySecondDiv");
var oController = new Controller();
</script>
</body>
</html>