Created
November 14, 2012 00:08
-
-
Save loadx/4069289 to your computer and use it in GitHub Desktop.
Ember-data server side validation without deadlocking the record as 'invalid'
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
App.AddContactController = Em.ArrayController.extend({ | |
init: function(){ | |
this.companies = App.store.findAll(App.Company); | |
}, | |
beginEdit: function(){ | |
// By default createRecord will add this to the ArrayProxy and it will be rendered | |
// this property allows us to toggle rendering | |
this.set('record', App.store.createRecord(App.Contact, {'visible': false})); | |
}, | |
save: function(){ | |
this.get('record').addObserver('stateManager.currentState.name', function(){ | |
var currentState = this.get('stateManager.currentState.name'); | |
if(currentState === 'saved'){ | |
// once the record was successfully saved we will render it | |
this.set('visible', true); | |
this.set('errors', []); | |
} | |
}); | |
App.store.commit(); | |
} | |
}); | |
In the adapter somewhere: | |
createRecord: function(store, type, record){ | |
var root = this.rootForType(type); | |
var data = {}; | |
data = this.toJSON(record, { includeId: true }); | |
this.ajax(this.buildURL(root), "POST", { | |
data: data, | |
context: this, | |
type: 'json', | |
statusCode: { | |
400: function(json){ | |
if(json.responseText.length > 0){ | |
store.recordWasInvalid(record, $.parseJSON(json.responseText)); | |
record.get('stateManager').send('becameValid'); | |
} | |
} | |
}, | |
success: function(json) { | |
this.didCreateRecord(store, type, record, json); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1 - this is very useful!