dojo - How to define a class just contains all constants variable? -
how can define class contains constants variable? late can refer constants other classes constants.car value("blue car") defined in constatns class. let say: car = "blue car" in constants class.
i've been working slightly-over-engineered solution because i'm little paranoid about:
- someone changing constants accident , screwing lot of stuff
- someone trying access nonexistent constant , not getting obvious error
so constant module looks like:
define(["dojo/_base/lang"], function(lang){ // variable private, never directly exposed outside world var constants = { foo : "alpha", bar : "beta" }; // if name of constant given, return associated variable. // if not, return constants, return copy potential // damage limited. return function(cname){ if(typeof cname == "undefined"){ // copy of our protected object return lang.clone(constants); }else{ // value of particular thing if(constants.hasownproperty(cname)){ return constants[cname]; }else{ throw "constant '"+cname+"' not exist."; } } }; });
to use constants, go:
require(["package/my/constants"],function(myconstants){ var x = myconstants("foo"); // should "alpha" var y = myconstants(); // should {foo:"alpha",bar:"beta"} }
given it's javascript, there's way subvert this, resistant against common mistakes.
Comments
Post a Comment