Search code examples
javascriptstringpublish-subscribe

How to build a namespace-like string using chained variables


This is a strange one, but I'm exploring it to see if it's possible.

Let's say that I have a .NET application where I am using PubSub. I want a way to define the topic string using chained objects (not functions). The goal is to allow me a way of defining strings that lets me to take advantage of Visual Studio's IntelliSense and reduce the likelihood of spelling errors.

Here's an example:

/* Manual way */
var topic = "App.Navigation.CurrentItem"



/* Desired Solution */

// ... define the objects here ...

var topic = App.Navigation.CurrentItem;
console.log(topic); // "App.Navigation.CurrentItem"

var topic2 = App.Footer.CurrentItem;
console.log(topic2); // "App.Footer.CurrentItem"

I'd like each object to be responsible for outputing it's own value, and have the chaining process responsible for joining itself to the previous chained object via a predefined separator (in my case, a period [.]).

I've been playing with JavaScript getter syntax, but I'm curious if there's a better way.

Has anyone done something like this before, and if so, how did you solve it?


Solution

  • You're requirements aren't totally clear to me, but are you looking for something like this?

    function namespace(ns) { this._ns = ns; }
    namespace.prototype.toString = function() {return this._ns};
    namespace.prototype.extend = function(suffix) {
        return new namespace(this._ns + "." + suffix)
    };
    

    Usage:

    App = new namespace('App');
    App.Navigation = App.extend('Navigation');
    App.Navigation.CurrentItem = App.Navigation.extend('CurrentItem');
    console.log(App.Navigation.CurrentItem.toString()); // "App.Navigation.CurrentItem"