Skip to content

Instantly share code, notes, and snippets.

@michael-brade
Last active October 9, 2015 23:26
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 michael-brade/874a1ba73ab1cd806303 to your computer and use it in GitHub Desktop.
Save michael-brade/874a1ba73ab1cd806303 to your computer and use it in GitHub Desktop.
DerbyJS: lesson about not using controller functions to get model data
# a simple function, but this will make real-time updates impossible
# it also causes DerbyJS to create new components with every keystroke
# get all subitems in item.attr -- and dereference them if needed
subitems: (item, attr) ->
data = item[attr.id]
return [] if not data
if not attr.multi
data = [data]
if not attr.reference
return data
# LiveScript automatically returns an array of these
for subitem in data
Api.instance!.item subitem, attr.entity # get the item for the subitem reference
<-html:>
{{each subitems(#item, #attr) as #subitem, #i}}
{{unless #i == 0}}
{{if #attr.id == 'name'}}
&nbsp;
{{else}}
<span>, &sp;</span>
{{/}}
{{/}}
<view name="item" item="{{#subitem}}" entity="{{#attr.entity}}" inherit />
{{/each}}
# Instead of doing the work ourselves, we only set up the model references!
# The setup takes a little bit of time but the updates later will be blazingly fast.
init: (model) !->
attr = @getAttribute 'attr'
subitems = model.at('item').at(attr.id)
if attr.multi
if attr.reference
# subitems contains array of references -> resolve them
items = model.root.at(attr.entity)
model.refList "subitems", items, subitems
else
# subitems contains array of items -> use that
model.ref "subitems", subitems
else
# subitems consists of either a single reference or a single item
# -> put it in an array with only one element
model.ref "_subitem.0", subitems
if attr.reference
# resolve item reference
items = model.root.at(attr.entity)
model.refList "subitems", items, "_subitem"
else
# use item directly
model.ref "subitems", "_subitem"
<-html:>
{{each subitems as #subitem, #i}}
{{unless #i == 0}}
{{if attr.id == 'name'}}
&nbsp;
{{else}}
<span>, &sp;</span>
{{/}}
{{/}}
<view name="item" item="{{#subitem}}" entity="{{attr.entity}}" inherit />
{{/each}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment