2015-10-05 36 views
1

這是一個很奇怪的問題,但我正在探索它,看看它是否可行。如何使用鏈接變量構建一個名稱空間類型的字符串

假設我有一個使用PubSub的.NET應用程序。我想要一種使用鏈接對象(而不是函數)定義主題字符串的方法。我的目標是讓我能夠定義字符串的方式,使我能夠利用Visual Studio的IntelliSense並降低拼寫錯誤的可能性。

下面是一個例子:

/* 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" 

我想每個對象負責outputing它自己的值,並有負責經由預定隔板接合本身到先前鏈接對象的鏈接處理(在我的情況下,一個時期[。])。

我一直在玩JavaScript getter語法,但我很好奇,如果有更好的方法。

有沒有人做過這樣的事情,如果是的話,你是如何解決它的?

+0

爲什麼你想鏈接過程負責建立字符串?爲什麼不有代碼只是說'App.Navigation.CurrentItem =「App.Navigation.CurrentItem」'? – StriplingWarrior

+0

我的工作是研發,所以我一直在設法讓我的團隊變得更容易。能夠定義一個變量來始終返回一個值,而不管它在鏈中的位置如何,這使我的代碼保持乾爽。老實說,沒有必要擁有。我只是好奇,如果有人有辦法使用JS來做到這一點。 –

回答

1

你的要求並不完全清楚,但你是否在尋找類似的東西?

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

用法:

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" 
+1

這完美 - 你釘了它!我不會想到這麼簡單。總體感覺,你已經在這裏教了我一些東西。擁抱感謝! –

0

這是我結束了審查StriplingWarrior的答案後:

function Namespace(name, config) { 
    if (typeof name === "object") { 
     config = name; 
     name = null; 
    } 
    config = config || {}; 

    this._ns = name; 
    this.define(config); 
} 
Namespace.prototype.toString = function() { return this._ns }; 
Namespace.prototype.define = function(config, base) { 
    base = base || this; 

    for (key in config) { 
     var name = (base._ns) ? base._ns + "." + key : key; 
     base[key] = new Namespace(name); 
     base.define(config[key], base[key]); 
    } 

    return base; 
}; 

用法:

var App = new Namespace("App", { 
    Navigation: { 
     Items: { 
      Current: {} 
     } 
    }, 
    Content: {}, 
    Footer: { 
     Items: { 
      Current: {} 
     } 
    } 
}); 

console.log(App.toString()); // App 
console.log(App.Navigation.Items.Current.toString()); // App.Navigation.Items.Current 
console.log(App.Footer.toString()); // App.Footer 

我也寫了一個方便的方法以減少toS tring():

function NS(namespace) { 
    return namespace.toString(); 
} 

console.log(NS(App.Navigation.Items.Current)); 

再次感謝StriplingWarrior的幫助!

相關問題