Skip to content

Instantly share code, notes, and snippets.

@talfco
Last active December 20, 2015 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save talfco/6079518 to your computer and use it in GitHub Desktop.
Save talfco/6079518 to your computer and use it in GitHub Desktop.
This is a cheatsheet for samples how to create objects dynamically
# Prerequisite there is a modelName.coffee class file in the corresponding folder
createObjectSample1 : (modelName) ->
new ( require "models/"+modelName)()
# This method only takes the className, supposing that require class loading took place
createObjectSample2: (strClass) ->
# Let's cache the Views
if window.cache[strClass] != undefined
log.debug("Approuter.newInstance: Reusing cached Instance "+strClass)
return window.cache[strClass]
else
log.debug("Approuter.newInstance: Creating new Object "+strClass)
# Arguments will be converted into an array, i.e. it means strClass
args = Array.prototype.slice.call arguments, 1
clsClass = eval strClass
F = () -> return clsClass.apply this, args
F.prototype = clsClass.prototype
window.cache[strClass] = new F()
return window.cache[strClass]
# http://stackoverflow.com/questions/5085095/create-object-from-dynamic-classname-reflectionclass-in-js
createObjectSample3: (strClass) ->
return new window[strClass]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment