Skip to content

Instantly share code, notes, and snippets.

@Nopik
Created January 23, 2014 11:08
Show Gist options
  • Save Nopik/8576850 to your computer and use it in GitHub Desktop.
Save Nopik/8576850 to your computer and use it in GitHub Desktop.
Ember patterns for custom models
#having Foo object, get some item:
item = foo.get( 'items' ).getBy( 'name', 'item1' )
#Feed this item to the view.
#if item is not loaded yet, is has isLoaded = false,
#so you can easily {{#if item.isLoaded}} {{item.name}} {{else}} Please wait, loading {{/if}} in your view
#you can load the item later on. Once deserialize will be called on foo, it will take care to fill in the item1 properties
#and set the isLoaded to true, automatically refreshing the view.
#Foo contains list of items
App.Foo = Ember.Object.extend
id: undefined
items: undefined
init: ->
@_super()
@set 'items', App.IdArray.create( { elementClass: App.Item, content: [] } )
deserialize: (json)->
#jsonExample = { id: 42, items: [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' } ] }
#Just call $.ajax to get json, feed the json here
@get( 'items' ).setCollectionBy 'name', json.items
delete json.items
@setProperties( json )
@set( 'isLoaded', true )
IdArrayMixin = Ember.Mixin.create
detectBy: (field, json_elem)->
elem = _.detect @get( 'content' ), (elem)->
elem.get( field ) == json_elem[ field ]
if !elem?
obj = { isLoaded: false }
obj[ field ] = json_elem[ field ]
elem = @addBy field, obj
elem
addBy: (field, obj)->
o = @elementClass.create( obj )
@addExistingBy field, o
addExistingBy: (field, o)->
idx = @getCurrentIndex(field, o)
@insertAt( idx, o )
o
getCurrentIndex: (field, o)->
idx = 0
while idx < @get('content').length
if @get('content')[ idx ].get( field ) >= o.get( field )
break
++idx
idx
getBy: (field_name, field_value)->
params = {}
params[ field_name ] = field_value
@detectBy( field_name, params )
findBy: (field, value)->
_.detect @get( 'content' ), (elem)-> elem.get( field ) == value
setCollectionBy: ( field, coll, sort = true)->
elems = {}
_.each @get( 'content' ), (elem)->
elems[ elem.get( field ) ] = elem
objs = []
_.each coll, ( elem )=>
e = elems[ elem[ field ] ]
if !e?
obj = { isLoaded: false }
obj[ field ] = elem[ field ]
e = @elementClass.create( obj )
elems[ elem[ field ] ] = e
objs.push e
e.deserialize( elem )
@pushObjects objs
if sort
@sortBy( field )
sortBy: (field)->
cnt = @get( 'content' ).sort (a,b)->
au = a.get( field )
bu = b.get( field )
return -1 if au < bu
return 1 if au > bu
0
cc = []
_.each cnt, (c)-> cc.push c
@set 'content', cc
App.Item = Ember.Object.extend
id: undefined
name: undefined
deserialize: (json)->
@setProperties( json )
@set( 'isLoaded', true )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment