3

I'm working with AngularJS on a browser game and I have a bunch of "business" constants.

These constants will be often updated during game testing (game balancing) and are used by different modules/features.

I'm currently managing them in a single file like that:

constants.js

var gameConstants = {
 BASE_COST: 100,
 MULTIPLIER_COST: 1.07
};

myFactory.js

app.factory('MyFactory', function () {
 return {
 getRealCost: function() {
 return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
 }
 }
});

But I'm thinking about a service provider for game constants. Something like:

constantServices.js

app.factory('ConstantServices', function () {
 var baseCost: 100, //Should I use UPPER_SNAKECASE here too?
 multiplierCost: 1.07
 return {
 getCost: function() {
 return baseCost;
 }
 getMultiplierCost: function() {
 return multiplierCost;
 }
 }
});

myFactory.js

app.factory('MyFactory', ['ConstantServices' function (ConstantServices) {
 return {
 getRealCost: function() {
 return ConstantServices.getCost() * ConstantServices.getMultiplierCost();
 }
 }
});

What do you think about it? Is it a good idea to create a service provider for constants only (i. e. call a service without any logic)? Do you think about a better way to manage these constants?

asked Sep 4, 2015 at 14:01
3
  • If your game balance constants are stored in client side JavaScript, you should be prepared for people to discover and alter those values. Commented Sep 4, 2015 at 14:08
  • @DanPichelman You're right, it's intended. The game has to be full client-side. Commented Sep 4, 2015 at 14:10
  • edit: re-worded; I see no reason why you shouldn't encapsule the gameConstants object inside the 'ConstantServices' factory and just expose it's values via the public interface of the service... Commented Sep 4, 2015 at 14:17

1 Answer 1

1

Just use the constant service from AngularJS:

app.constant('gameConstants, [ 
 { BASE_COST: 100 },
 { MULTIPLIER_COST: 1.07 }
]);

And then inject the gameConstants wherever you need them:

app.factory('MyFactory', ['gameConstants', function (gameConstants) {
 return {
 getRealCost: function() {
 return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
 }
 }
}]);
answered Sep 5, 2015 at 8:11
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.