Search code examples
dojostore

share a dojo/store between different widgets


Is there a pattern to share a single dojo/store between multiple widgets?

I have multiple widgets on the same page that use the same dojo/store, and I don't want to duplicate it, so I don't need to make the same REST calls twice.


Solution

  • Consider creating a separate module where you store state and operations for your dojo/store. The module will contains an "API' that your widgets can access.

    Below a very simple example using the single tone pattern.

    define([], function () {
       'use strict';
    
        var _instance;
        function _StoreManager() {
        }
        _StoreManager.prototype = {
            _privateMember: null,
            getDataFromApi: function () { 
                //...
            },
            saveDataToApi: function (data) {
                //...
            },
        };
        return function _getSingleton() {
            // summary:
            //      Gets singleton object.
            return (_instance = (_instance || new _StoreManager()));
        };
    });
    

    Require the module and use it.

    require(['_StoreManager'],function(_StoreManager){
       _StoreManager.saveDataToApi({});
    });