So, a colleague introduced me to the publish/subscribe pattern (in JS/jQuery), but I\'m having a hard time getting to grips with why one would use this pattern over
So that you don't have to hardcode method / function calls, you just publish the event without caring who listens. This makes the publisher independent from subscriber, reducing dependency (or coupling, whatever term you prefer) between 2 different parts of the application.
Here are some disadvantages of coupling as mentioned by wikipedia
Tightly coupled systems tend to exhibit the following developmental characteristics, which are often seen as disadvantages:
- A change in one module usually forces a ripple effect of changes in other modules.
- Assembly of modules might require more effort and/or time due to the increased inter-module dependency.
- A particular module might be harder to reuse and/or test because dependent modules must be included.
Consider something like an object encapsulating business data. It has hard coded method call to update the page whenever the age is set:
var person = {
name: "John",
age: 23,
setAge: function( age ) {
this.age = age;
showAge( age );
}
};
//Different module
function showAge( age ) {
$("#age").text( age );
}
Now I cannot test the person object without also including the showAge
function. Also,
if I need to show the age in some other GUI module as well, I need to hardcode that method call in
.setAge
, and now there is dependencies for 2 unrelated modules in the person object. It's also just
hard to maintain when you see those calls being made and they are not even in the same file.
Note that inside the same module, you can of course have direct method calls. But business data and superficial gui behavior should not reside in the same module by any reasonable standards.