Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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