Search code examples
javascriptcookiesdojowidget

Intercepting response in dojo to read cookies


I have a filter on server side which adds a cookie myCookie to every response.

I am intercepting the response in a dojo widget as below:

define("mySolution/ServerCookieWidget", [
"dojo/request/notify",
"dojo/cookie"
], function (notify, cookie) {
notify("load", function(response) {
     var cookieRead = cookie("myCookie");
     console.log('Cookie read is: ', cookieRead);
    });
});

I want to use the value read to do some calculation on client side.

How do I share the read cookie value with other widget?

I am new to dojo and thus not aware of the syntax and not able to find any example for my scenario.


Solution

  • Depending on the rest of your architecture, you might want to use Dojo's pubsub module dojo/topic:

    https://dojotoolkit.org/reference-guide/1.10/dojo/topic.html

    So for example, changing your code to:

    define("mySolution/ServerCookieWidget", [
        "dojo/request/notify",
        "dojo/cookie",
        "dojo/topic"
    ], function (notify, cookie, topic) {
        notify("load", function(response) {
            var cookieRead = cookie("myCookie");
            // console.log('Cookie read is: ', cookieRead);
            topic.publish("*/cookie/value", cookieRead);
        });
    });
    

    You can create widgets which subscribe to the topic:

    define("mySolution/SomeOtherWidget", [
        "dojo/_base/declare",
        "dojo/topic"
    ], function (declare, topic) {
        var OtherWidget = declare(null, {
            constructor: function (opt) {
               this.topicHandle = topic.subscribe("*/cookie/value", this._handleCookieValue.bind(this));
            },
            _handleCookieValue: function (cookieVal) {
                console.log("Cookie value is:", cookeVal);
            }
        });
    
        return OtherWidget;
    });