Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is a cheatsheet for samples how to create objects dynamically
# Prerequisite there is a 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]
log.debug("Approuter.newInstance: Creating new Object "+strClass)
# Arguments will be converted into an array, i.e. it means strClass
args = arguments, 1
clsClass = eval strClass
F = () -> return clsClass.apply this, args
F.prototype = clsClass.prototype
window.cache[strClass] = new F()
return window.cache[strClass]
createObjectSample3: (strClass) ->
return new window[strClass]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment