Created
November 11, 2014 15:47
-
-
Save benqus/9416627c20cfef93eae2 to your computer and use it in GitHub Desktop.
Simple Mediator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mediator = { | |
siblings: [], | |
notify: function () { | |
var args = Array.prototype.slice.call(arguments); | |
this.siblings.forEach(function (sibling) { | |
sibling.onNotify.apply(sibling, args); | |
}); | |
}, | |
add: function (sibling) { | |
if (this.siblings.indexOf(sibling) === -1 && typeof sibling.onNotify === 'function') { | |
this.siblings.push(sibling); | |
} | |
}, | |
remove: function (sibling) { | |
var index = this.siblings.indexOf(sibling); | |
if (index > -1) { | |
this.sibling.splice(index, 1); | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Sibling() { | |
mediator.add(this); | |
this.id = Sibling.getUniqueID(); | |
} | |
Sibling.getUniqueID = (function () { | |
var id = 0; | |
return function () { | |
return id++; | |
}; | |
}()); | |
Sibling.prototype.onNotify = function () { | |
console.log(this.id); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment