Skip to content

Instantly share code, notes, and snippets.

@mariusGundersen
Last active November 18, 2016 04:00
Show Gist options
  • Save mariusGundersen/7364253 to your computer and use it in GitHub Desktop.
Save mariusGundersen/7364253 to your computer and use it in GitHub Desktop.
Weak event listeners
var component1 = {
//this method will receive the event and process it
handleEvent: function(event){
//this is only for debugging
console.log("debugging!", event.data);
//the event causes the state of the component to change
this.content = event.data;
},
content: ""
};
//component1.handleEvent will be called when someEvent is triggered
System.addWeakEventListener("someEvent", component1, "handleEvent");
//trigger the event
System.dispatchEvent("someEvent", "someData");
//this causes a debug message to appear in the console log
component1.content == "someData" //true
component1 = null;
//component1 is garbage collected
//trigger the event again
System.dispatchEvent("someEvent", "someData");
//nothing happens, since the component is garbage collected
//In this example we have two dom elements which communicate through weak event listeners.
//They are not kept alive by each other, even though they can directly interact
//lets create a form for adding users to a list.
var input = document.createElenent("input");
var button = document.createElement("button");
button.onclick = function(){
System.dispatchEvent("addUser", input.value);
};
document.body.appendChild(input);
document.body.appendChild(button);
//now we create the list
var list = document.createElement("ul");
list.whenUserIsAdded = function(event){
var item = document.createElement("li");
item.textContent = event.data;
this.appendChild(item);
};
//when the button is clicked, a new <li> will be added to the <ul>
System.addWeakEventListener("addUser", list, "whenUserIsAdded");
//add the list to the page as well
document.body.appendChild(list);
list = null;
//wait 5 minutes, then remove the list
setTimeout(function(){
//remove the last strong reference to the list, destroying it!
document.body.removeNode(document.body.childNodes[2]);
}, 1000*60*5);
@roblav96
Copy link

whats System?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment