YUI, instantiable module that is not a widget?

72 views Asked by At

If I want a module that is instantiable, let say, a module that handles storing preferences in a subcookies, and i want the main cookie to be configurable, but i don't want it to be a widget... what patterns should i use with YUI?

the end code should be something:

Y.use('my-pref-manager', function(Y){
    var A = Y.my-pref-manager.prefStore('A"),
        B = Y.my-pref-manager.prefStore('B");
    // A and B are now loaded with the contents of cookies A and B, if they exist
    A.set('xy', 123 );
});

So far i either found patterns that create widgets within my-module or i have to use methods directly in my-method which will be globals and lack initializers, etc.

1

There are 1 answers

0
Jonas G. Drange On

There is a bunch of ways of doing this. You could do it using Y.Base.create, like below. The code might not be production ready, or even working properly, but hopefully it answers how you can create a module without it being a Widget.

The code below creates a module that extends Y.Base. This let us use Attributes and other cool things. Check the doc for Y.Base.

YUI.add('my-pref-manager', function (Y) {

    var PrefManager = Y.Base.create('myPrefManager', Y.Base, [], {

        initializer: function () {
            this.after('prefsChange', this.changePref);
        },

        changePref: function (e) {
            Y.Cookie.setSub(this.get('prefStore'), e.subAttrName, this.get(e.subAttrName));
        },

        setPref: function (name, val) {
            this.set('prefs.'+name, val);
        },

        getPref: function (name) {
            return this.get('prefs.'+name);
        }


    }, {
        ATTRS: {
            prefStore: { 
                value: null,
                setter: function (val) {
                    return Y.Cookie.set(val, val);
                }
            },
            prefs: {
                value: {}
            }
        }
    });

    Y.namespace('My').PrefManager = PrefManager;

}, '0.0.1', {
    requires: ['base', 'cookie']
});

YUI().use('my-pref-manager', function (Y) {
    var A = new Y.My.PrefManager({prefStore: 'userPrefs'}),
        B = new Y.My.PrefManager({prefStore: 'displayPrefs'});

    A.setPref('x', 3);
    A.setPref('y', 54);

    B.setPref('tty', 7);

    console.log(A.getPref('x')); // 3
});

Try it out: http://jsfiddle.net/B62nu/