Why would one use the Publish/Subscribe pattern (in JS/jQuery)?

前端 未结 7 409
无人及你
无人及你 2020-11-30 16:25

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

相关标签:
7条回答
  • 2020-11-30 16:48

    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:

    1. A change in one module usually forces a ripple effect of changes in other modules.
    2. Assembly of modules might require more effort and/or time due to the increased inter-module dependency.
    3. 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.

    0 讨论(0)
提交回复
热议问题