So i built my first application in SproutCore. An IP-Management application which fetches available IP-addresses from the inventorysystem my department uses.
It was really easy to build the application using fixtures and when my datasource and backend was ready i just switched the store to "store: SC.Store.create().from("MyApp.DataSource")," and i had real data in my application!
Basically MyApp.DataSource is a base set of functions which is called when certain functions are called. As i dont have any need to write data back to the server in this application i only have use for fetch().
My fetch-function passes what store made the request and what query was used:
fetch: function(store, query) {
// Check what query was used. Add more else if, if your application handles more data-models
if (query === SC.Query.remote(MyApp.Subnet)) {
//Initiate a server request for all the subnets available in JSON-format
var serverRequest = SC.Request.getUrl('/data/subnet').json();
//Tell SproutCore what object and what function it should call up a response, pass query and store
serverRequest.notify(this, this._didFetchAllSubnets, { query: query, store: store });
//I want all my data loaded before continuing
serverRequest.set('isAsynchronous', NO);
//Finally, send the request
serverRequest.send();
//return YES (true) to indicate we handled the fetch.
return YES;
}
}
The function which will be called upon a response is "_didFetchAllSubnets" as specified in the .notify() function above. This function needs to call at least 2 functions upon reading the data, check out this function:
_didFetchAllSubnets: function(response, params) {
//Get the parameters passed from the request
var store = params.store;
var query = params.query;
// Only if the response is ok we would want to read it into the store
if (SC.$ok(response)) {
// load the data into the store and save the storeKeys
storeKeys = store.loadRecords(MyApp.Subnet, response.get('body').content);
// notify store that we handled the fetch and hand it the storeKeys
store.dataSourceDidFetchQuery(query,storeKeys);
// handle error case
} else store.dataSourceDidErrorQuery(query, response);
},
And that reads the data into the local store and can be presented. One thing i learned is that if ur missing one of the specified fields in the data-model, it wont be able to use the data. I missed out on the guid (this was generated just before sending the data from my php-script), i had it commented for some reason. This generated an error of "dataHashes.len is not a function".
Almost every line of this code is taken from http://wiki.sproutcore.com/DataStore-Introduction
Inga kommentarer:
Skicka en kommentar