Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript generating dynamic variable names for objects (named classes)

I'm pretty new to the world of JavaScript and even newer to CoffeeScript. I have a problem and I'm not sure if it's even possible.

Say I have a CoffeeScript class like this

class @Model
  constructor: (@name) ->

how could I pass the names of models to be created to a function to instantiate these objects whilst appending the name of the variable [in this case] with _model? Something like:

makeModel = (name) ->
  "#{name}_model" = new Model(name)

My rails app tells me that:

unexpected =
      "#{name}_model" = new Model(
                ^

I'm assuming that this is because of the string. Is there some sort of method to convert a string to a variable name? I took a quick look at the .eval() method but the little book of CoffeeScript warns against it's use.

Thanks

like image 998
DazBaldwin Avatar asked May 31 '26 09:05

DazBaldwin


1 Answers

You could do something like this:

ModelFactory = do -> 
  class @Model
    constructor: (@name) ->

  models = {}

  makeModel = (name) ->
    model = new Model(name)
    models["#{name}Model"] = model
    model

  getModel = (name) ->
    models["#{name}Model"] or makeModel(name)

  { getModel }

Secret Magic:

do -> - The do keyword creates an IIFE, a function that is called as soon as it is created. It can be used for creating modules like the following:

var myModule = (function () {
    var privateFunc = function () {};
    var publicFunc = function () { privateFunc(); };
    return {
        publicFunc: publicFunc
    }
})();

accessing properties with strings - In JavaScript, you can access a property of an object as a string, by using the square-bracket ([]) notation, plus a string, or a variable containing a string. Here we are combining this with the CoffeeScript string interpolation sugar ("#{}") to dynamically create property names and assign them.

var object = {
    prop: 'value',
    otherProp: 'otherValue'
};

var propertyName = 'prop';
var value = object[propertyName]; // 'value';

var something = 'Something'
object['my' + something] = 'a new property';
object.mySomething === 'a new property'; // true
like image 117
phenomnomnominal Avatar answered Jun 01 '26 21:06

phenomnomnominal