Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Observer pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===JavaScript=== JavaScript has a deprecated {{code|Object.observe}} function that was a more accurate implementation of the observer pattern.<ref>{{Cite web|url=https://stackoverflow.com/a/50862441/887092|title = jQuery - Listening for variable changes in JavaScript}}</ref> This would fire events upon change to the observed object. Without the deprecated {{code|Object.observe}} function, the pattern may be implemented with more explicit code:<ref>{{Cite web|url=https://stackoverflow.com/a/37403125/887092|title = Jquery - Listening for variable changes in JavaScript}}</ref> <syntaxhighlight lang="js"> let Subject = { _state: 0, _observers: [], add: function(observer) { this._observers.push(observer); }, getState: function() { return this._state; }, setState: function(value) { this._state = value; for (let i = 0; i < this._observers.length; i++) { this._observers[i].signal(this); } } }; let Observer = { signal: function(subject) { let currentValue = subject.getState(); console.log(currentValue); } } Subject.add(Observer); Subject.setState(10); //Output in console.log - 10 </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)