Created
September 28, 2014 21:07
-
-
Save sararob/26e0a80b1fb5d1aad9d5 to your computer and use it in GitHub Desktop.
Example of implementing a hasMany / belongsTo relationship in EmberFire
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var App = Ember.Application.create({}); | |
var Promise = Ember.RSVP.Promise; | |
// ADAPTER | |
App.ApplicationAdapter = DS.FirebaseAdapter.extend({ | |
firebase: new Firebase("https://<your-firebase-name>.firebaseio.com/") | |
}); | |
// MODELS | |
App.Bar = DS.Model.extend({ | |
name: DS.attr('string'), | |
city: DS.attr('string'), | |
deals: DS.hasMany('deal', { async: true }) | |
}); | |
App.Deal = DS.Model.extend({ | |
title: DS.attr('string'), | |
description: DS.attr('string') | |
}); | |
// ROUTES | |
App.Router.map(function() { | |
this.resource('bars', { path: '/bars' }, function() { | |
this.route('new'); | |
}); | |
this.resource('bar', { path: '/bar/:bar_id'}); | |
}); | |
App.BarsIndexRoute = Ember.Route.extend({ | |
model: function() { | |
return this.store.findAll('bar'); | |
} | |
}); | |
App.BarRoute = Ember.Route.extend({ | |
model: function(params) { | |
return this.store.find('bar', params.bar_id); | |
} | |
}); | |
// CONTROLLERS | |
App.BarsNewController = Ember.ObjectController.extend({ | |
init: function() { | |
this.set('bar', Ember.Object.create()); | |
}, | |
actions: { | |
addBar: function() { | |
var newBar = this.store.createRecord('bar', { | |
name: this.get('bar.name'), | |
city: this.get('bar.city') | |
}); | |
newBar.save(); | |
this.setProperties({ | |
'bar.name':'', | |
'bar.city':'' | |
}); | |
this.transitionToRoute('bars'); | |
} | |
} | |
}); | |
App.BarController = Ember.ObjectController.extend({ | |
actions: { | |
addDeal: function(bar, deal) { | |
deal.save().then(function() { | |
Promise.cast(bar.get('deals')).then(function(deals) { | |
deals.addObject(deal); | |
bar.save().then(function() {}, function() {}); | |
}); | |
}); | |
} | |
} | |
}); | |
// COMPONENTS | |
App.FireBarComponent = Ember.Component.extend({ | |
actions: { | |
addDeal: function() { | |
var store = this.get('targetObject.store'); | |
var deal = store.createRecord('deal', { | |
title: this.get('dealTitle'), | |
description: this.get('dealDescription') | |
}); | |
this.sendAction('onAddDeal', this.get('bar'), deal); | |
this.setProperties({ | |
dealTitle: '', | |
dealDescription: '' | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment