Skip to content

Instantly share code, notes, and snippets.

@jasonmit
Last active August 29, 2015 14:12
Show Gist options
  • Save jasonmit/c77af23a95fd7aeeb8ec to your computer and use it in GitHub Desktop.
Save jasonmit/c77af23a95fd7aeeb8ec to your computer and use it in GitHub Desktop.
Ember-data custom didCreateRecord event
/*
* The `didCreate` event on a DS.Model does not behave like one would expect.
* It actually only ever fires when you createRecord AND then save the record.
*
* This custom eventing below is how you achieve a the expected event.
* This is useful in the case where you have relational objects that you want
* to auto-create when a record is created. Or, some custom logic to implement
* once the record is created. Likely very useful where you want to setup
* observers for things like validation. Placing them in `init` wouldn't
* be ideal since they will trigger the first time the model is initialized
* and sets its initial values.
*
* Demo: http://emberjs.jsbin.com/juyejacaje/1/edit?html,js,console,output
*/
App = Ember.Application.create({});
App.ApplicationStore = DS.Store.extend({
createRecord: function () {
var out = this._super.apply(this, arguments);
out.triggerLater('didCreateRecord');
return out;
}
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('foo', {
bar: 'baz'
});
}
});
App.Foo = DS.Model.extend({
bar: DS.attr('string'),
doSomething: function(){
console.log('didCreateRecord triggered');
}.on('didCreateRecord')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment