JSFiddle - React, Tailwind, and code Playground
by 533135
HTML
<button id="addNewObserver">Add New Observer checkbox</button>
<input id="mainCheckbox" type="checkbox"/>
<div id="observersContainer"></div>
JavaScript
function ObserverList(){
this.observerList = [];
}
ObserverList.prototype.Add = function( obj ){
return this.observerList.push( obj );
};
ObserverList.prototype.Get = function( index ){
if( index > -1 && index < this.observerList.length ){
return this.observerList[ index ];
}
};
ObserverList.prototype.Count = function(){
return this.observerList.length;
};
// Extend an object with an extension
function extend( extension, obj ){
for ( var key in extension ){
obj[key] = extension[key];
}
}
function Subject(){
this.observers = new ObserverList();
}
Subject.prototype.AddObserver = function( observer ){
this.observers.Add( observer );
};
Subject.prototype.RemoveObserver = function( observer ){
this.observers.RemoveAt( this.observers.IndexOf( observer, 0 ) );
};
Subject.prototype.Notify = function( context ){
var observerCount = this.observers.Count();
for(var i=0; i < observerCount; i++){
this.observers.Get(i).Update( context );
}
};
Subject.prototype.Notify2 = function( ){
alert("sdfsdf")
};
// The Observer
function Observer(){
this.Update = function(){
// ...
alert("new update")
};
}
// References to our DOM elements
$(document).ready(function(){
var controlCheckbox =document.getElementById( "mainCheckbox" ),// $("#mainCheckbox" ),
addBtn = $("#addNewObserver" ),
container = $("#observersContainer" );
// Extend the controlling checkbox with the Subject class
extend( new Subject(), controlCheckbox );
$("#mainCheckbox" ).click(function(){
controlCheckbox.Notify(controlCheckbox.checked)
})
addBtn["click"](AddNewObserver);
function AddNewObserver(){
// Create a new checkbox to be added
var check = document.createElement( "input" );
check.type = "checkbox";
check.id = Math.random()+"_checkbox";
// Extend the checkbox with the Observer class
extend( new Observer(), check );
// Override with custom update behaviour
check.Update = function(...