Automating The Publish/Subscribe Pattern In JavaScript

Automating the Publish/Subscribe Pattern in JavaScript

The Publish/Subscribe pattern is one of the most used patterns in software, especially in User Interfaces with JavaScript. It is used whenever 2 pieces of a system need to communicate, but cannot or should not communicate directly. For example, a system receives data from a server at regular intervals that a bunch of components can use (which are added while the system runs):

var Publisher = function() { var self = { subscribers: [] }; self.subscribe = function(callback) { self.subscribers.push(callback); }; self.publish = function(data) { self.subscribers.forEach(function(callback) { callback(data); }); }; return self; } var publisher = Publisher(); // Simulate a set of data being returned over time var serverStream = function(callback) { Array.apply(null, { length: 5 }).forEach(function(unused, index) { var ms = index * 500 setTimeout(function() { callback('data-piece: ' + ms + ' ms'); }, ms); }); }; serverStream(publisher.publish); // Simulate components being registered over time. publisher.subscribe(function(data) { console.info('subscribe from part 1', data); }); setTimeout(function() { publisher.subscribe(function(data) { console.info('subscribe from part 2', data); }); }, 1000) // subscribe from part 1 data-piece: 0 ms // subscribe from part 1 data-piece: 500 ms // subscribe from part 1 data-piece: 1000 ms // subscribe from part 1 data-piece: 1500 ms // subscribe from part 2 data-piece: 1500 ms // subscribe from part 1 data-piece: 2000 ms // subscribe from part 2 data-piece: 2000 ms

The problem is that same pattern with almost identical code will be written over and over again in the same project. So instead of creating a publisher and subscriber with multiple message types each time this pattern needs to be used, it is simpler to just use new instances of the publisher object each time:

var messageSet1 = function(callback) { Array.apply(null, { length: 3 }).forEach(function(unused, index) { setTimeout(function() { callback('Hello ' + index); }, index * 500); }); }; var messageSet2 = function(callback) { Array.apply(null, { length: 3 }).forEach(function(unused, index) { setTimeout(function() { callback('World ' + index); }, index * 500); }); }; var MessageBox = function() { var self = { publishers: [] }; self.streams = function(streams) { self.publishers = []; streams.forEach(function(stream, index) { self.publishers.push(Publisher()); stream(self.publishers[index].publish); }); }; self.subscribeTo = function(index, callback) { return self.publishers[index].subscribe(callback); } return self; }; var messageBox = MessageBox(); // Use a trivial example to preserve clarity messageBox.streams([messageSet1, messageSet2]); messageBox.subscribeTo(0, function(data) { console.info('subscribe from part 1B', data); }); messageBox.subscribeTo(1, function(data) { console.info('subscribe from part 2B', data); }); // subscribe from part 1B Hello 0 // subscribe from part 2B World 0 // subscribe from part 1B Hello 1 // subscribe from part 2B World 1 // subscribe from part 1B Hello 2 // subscribe from part 2B World 2

A non-index based naming scheme could be introduced by passing more data into the streams call, but I wanted to keep the example as minimal as possible.

Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/publishSubscribeAutomation.js

More Posts from Nuttymilkshakedreamland-blog and Others

NASA Astronomy Picture Of The Day 2016 September 4 

NASA Astronomy Picture of the Day 2016 September 4 

Io over Jupiter from Voyager 1 

Back in 1979, NASA’s Voyager 1 spacecraft flew past Jupiter and its moons. The images in this mosaic, featuring the moon Io against a background of gas giant Jupiter’s diffuse swirling cloud bands, were recorded by Voyager’s camera from a distance of about 8.3 million kilometers. The Io image from this mosaic may be the first to show curious round features on Io’s surface with dark centers and bright rims more than 60 kilometers across. Now known to be volcanic in origin, these features were then thought likely to be impact craters, commonly seen on rocky bodies throughout the Solar System. But as Voyager continued to approach Io, close-up pictures revealed a bizarre world devoid of impact craters, frequently resurfaced by volcanic activity. Earlier this year a new robotic spacecraft, NASA’s Juno, began to orbit Jupiter and last week made a pass within 5,000 kilometers of Jupiter’s clouds. During the next two years, it is hoped that Juno will discover new things about Jupiter, for example what’s in Jupiter’s core.

Save Your Computer

I have the worst luck. I’ve broken five computers and four laptops but I’ve finally learnt my lesson. After losing my work so many times, I have been great at rewriting because I’d never backed anything up. Take it from me:

Even if you backup your work in one external source from your computer, back it up online or in as many places as you can

Back up according to how much valuable work you have so if you save work/programs frequently, back up once every week

If you have a Windows computer, go onto Control Panel and search “back up”. Click on the first link and follow through from there

Do not wait until it’s too late

I may add more information on if I can think of any, but here are some useful links on some other ways to back up your computer: Windows help to backing up files How to Back Up a Computer (among other devices) How to Back up Data The absurdly simple guide to backing up your PC Three Best Ways to Back Up Your Files 6 cheap ways to back up your files 8 Ways to Back up Your Computer Files How to back up your data Done a Computer Backup Lately?

me on the outside looking in at Louis and Harry, hand against the glass: you’re doing so good kids….

me: damn I hate winter GIVE ME SPRING AND SUMMER

spring starts, bugs start coming out

me: take me back to winter

Software engineering (SE)

is the application of a systematic, disciplined, quantifiable approach to the design, development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software

Save Your Computer

I have the worst luck. I’ve broken five computers and four laptops but I’ve finally learnt my lesson. After losing my work so many times, I have been great at rewriting because I’d never backed anything up. Take it from me:

Even if you backup your work in one external source from your computer, back it up online or in as many places as you can

Back up according to how much valuable work you have so if you save work/programs frequently, back up once every week

If you have a Windows computer, go onto Control Panel and search “back up”. Click on the first link and follow through from there

Do not wait until it’s too late

I may add more information on if I can think of any, but here are some useful links on some other ways to back up your computer: Windows help to backing up files How to Back Up a Computer (among other devices) How to Back up Data The absurdly simple guide to backing up your PC Three Best Ways to Back Up Your Files 6 cheap ways to back up your files 8 Ways to Back up Your Computer Files How to back up your data Done a Computer Backup Lately?

Invest in yourself in 2016.

(via deeplifequotes)

List to help you code, script, & program (from imgur)

**NOT MINE** 

Reposting in case the original source is lost someday. Check back on the original though; OP said he would keep it updated.

SOURCE

After seeing a list of pretty much only frameworks, with no actual learning resources I decided to throw together an actual list of resources. I will admit my personal focus has always been front & backend web, so this list may be a little biased. I’m sure I missed some and skipped some, sorry.

========== LEARNING ==========

Codecademy - https://www.codecademy.com //Multi Languages 

SoloLearn - http://www.sololearn.com //Multi Languages 

TutorialsPoint - http://www.tutorialspoint.com //Multi Languages 

thenewboston - https://www.youtube.com/user/thenewboston //Multi Languages 

Derek Banas - https://www.youtube.com/user/derekbanas //Multi Languages 

Coursera - https://www.coursera.org  //Multi Languages 

TechRocket - https://www.techrocket.com //Multi Languages 

FreeCodeCamp - http://www.freecodecamp.com //Web Languages 

The Odin Project - http://www.theodinproject.com //Web Languages 

DataCamp - https://www.datacamp.com //R 

Learn-C - http://www.learn-c.org 

Learn C++ - http://www.learncpp.com 

Learn  C# - http://www.learncs.org 

Learn Python - http://www.learnpython.org 

Think Python - http://greenteapress.com/wp/think-python 

Learn Java - http://www.learnjavaonline.org 

Learn JavaScript - http://www.learn-js.org 

Learn PHP - http://www.learn-php.org

========== HOME PAGES ========== 

 PHP.net - http://php.net 

ASP.net - http://www.asp.net 

Ruby - https://www.ruby-lang.org/en 

Ruby On Rails - http://rubyonrails.org 

Python - https://www.python.org 

Java - http://java.com/en/download/faq/develop.xml 

MySQL - https://www.mysql.com 

PostgreSQL - http://www.postgresql.org 

sqLite - https://www.sqlite.org 

Lua - http://www.lua.org 

 ========== REFERENCES ========== 

MDN - https://developer.mozilla.org/en-US //Web Documentation & Tools 

Stackoverflow - http://stackoverflow.com //Large Question Forum 

GitHub - https://github.com //Repository 

W3School - http://www.w3schools.com //Web Documentation. Contains some outdated or wrong info, but not terrible for quick references 

W3C - https://www.w3.org //Web Standards 

 ========== PLAYGROUNDS ========== 

JSFiddle - https://jsfiddle.net 

CodePen - http://codepen.io 

JS Bin - http://jsbin.com 

CodePad - http://codepad.org 

PHP Fiddle - http://phpfiddle.org 

SQLFiddle - http://sqlfiddle.com 

RegEx101 - https://regex101.com 

txt2re - http://txt2re.com 

CheckiO - http://www.checkio.org 

 ========== Editors / Clients ==========

NotePad++ - https://notepad-plus-plus.org //windows 

SublimeText - https://www.sublimetext.com //windows & OSX & Ubuntu 

Atom - https://atom.io //Windows & OSX & Ubuntu & Linux 

Coda - https://panic.com/coda //osx 

TextWrangler - http://www.barebones.com/products/textwrangler //osx 

Brackets - http://brackets.io 

Cloud9 - https://c9.io //Dev in the Cloud 

VIM - http://www.vim.org //Cross platform 

Emacs - https://www.gnu.org/software/emacs //Cross platform 

Putty - http://www.putty.org //windows 

iTerm2 - https://www.iterm2.com //osx 

phpMyAdmin - https://www.phpmyadmin.net //browser based 

FileZilla - https://filezilla-project.org //windows 

Cyberduck - https://cyberduck.io/?l=en //osx 

Transmit - https://panic.com/transmit  //osx 

MATLab - http://www.mathworks.com/products/matlab 

 ========== Frameworks / Helpers ========== 

====== DO NOT JUST JUMP INTO THESE ======= 

============ LEARN FIRST ============= 

=========  There are tons more  ========== 

— HTML & CSS — 

Bootstrap - http://getbootstrap.com 

HTML5 BoilerPlate - https://html5boilerplate.com 

LESS - http://lessframework.com 

SASS - http://sass-lang.com 

 — Javascript — 

jQuery - http://jquery.com 

Prototype - http://prototypejs.org 

YUI - http://yuilibrary.com 

React - https://facebook.github.io/react 

Angular - https://angularjs.org 

 — PHP — 

Zend - http://framework.zend.com 

Cake - http://cakephp.org 

Laravel - https://laravel.com 

Symfony - http://symfony.com 

yii - http://www.yiiframework.com/wiki/?tag=yii2 

 — Ruby — 

Rails - http://rubyonrails.org 

Sinatra - http://www.sinatrarb.com 

Ramaze - http://ramaze.net 

 — Python — 

Django - https://www.djangoproject.com 

Gears - http://turbogears.org 

Cherry - http://www.cherrypy.org 

Flask - http://flask.pocoo.org 

 — Perl — 

Catalyst - http://www.catalystframework.org 

Mojolicious - http://mojolicio.us 

 — Java — 

Spring - http://spring.io 

Play - https://www.playframework.com 

Dropwizard - http://www.dropwizard.io 

Eclipse - https://eclipse.org/downloads 

IntelliJ - https://www.jetbrains.com/idea

========== PERSONAL TIPS ==========

// Stay hydrated. I recommend Mt Dew, Monster, or Red Bull //The last line was sarcasm, these drinks do not hydrate you. Drink water for hydration. Green tea, coffee and dark chocolate can be good (moderation matters) sources for an extra energy boost. // Comment heavy, comment often. You may know what you’re doing at 4:30am, but when you revisit that code in 2 months you can quickly become your own wost enemy. // When switching languages, remember your syntax. + is not . // A semicolon can make or break you // KISS - Keep It Simple, Stupid. What seems to be the most complex problem is usually the easiest solution; e.g. after debugging  for an hour, remember you changed a default in your table from 0 to NULL and that is why our code is breaking … not that I’ve ever done that; especially not last night.

“ Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” -Martin Golding

“ A good programmer is someone who always looks both ways before crossing a one-way street.” -Doug Linder

“Programming is like sex. One mistake and you have to support it for the rest of your life.” -Michael Sinz

SOURCE

  • siskanajma-blog
    siskanajma-blog liked this · 7 years ago
  • update-package-reinstall
    update-package-reinstall reblogged this · 8 years ago
  • samedis-stuff
    samedis-stuff reblogged this · 8 years ago
  • joejupiter-blog1
    joejupiter-blog1 liked this · 8 years ago
  • kevintjeb-blog
    kevintjeb-blog liked this · 8 years ago
  • bforborna-blog
    bforborna-blog reblogged this · 8 years ago
  • eclipsedcode
    eclipsedcode liked this · 8 years ago
  • nuttymilkshakedreamland-blog
    nuttymilkshakedreamland-blog reblogged this · 8 years ago
  • kbzmama
    kbzmama liked this · 8 years ago
  • silva-marlon-blog
    silva-marlon-blog liked this · 8 years ago
  • aviner
    aviner reblogged this · 8 years ago
  • grafises-blog
    grafises-blog liked this · 8 years ago
  • lemuenic
    lemuenic liked this · 8 years ago
  • codecartooning
    codecartooning liked this · 8 years ago
  • carlochess
    carlochess liked this · 8 years ago
  • wimagine
    wimagine liked this · 8 years ago
  • remyhowlett-blog
    remyhowlett-blog liked this · 8 years ago
  • nagyzol
    nagyzol liked this · 8 years ago
  • siriusqbot
    siriusqbot reblogged this · 8 years ago
  • inferno3210
    inferno3210 liked this · 8 years ago
  • theconqueringfool
    theconqueringfool liked this · 8 years ago
  • giraffebears
    giraffebears reblogged this · 8 years ago
  • giraffebears
    giraffebears liked this · 8 years ago
  • ulrikkold
    ulrikkold liked this · 8 years ago
  • stephnewland
    stephnewland liked this · 8 years ago
  • obscurejavascript
    obscurejavascript reblogged this · 8 years ago

71 posts

Explore Tumblr Blog
Search Through Tumblr Tags