30-second Tutorial on Models

To Create a New Model

In your terminal:


cd project-name
sc-gen model contacts/contact

This creates:

 

  • The model file in clients/contacts/models/contact.js
  • The unit test in clients/contacts/tests/models/contact.js
  • A fixtures file in clients/contacts/fixtures/contact.js

 

To Create Some Models

The attributes you get from the server should be simple JSON hashes.  They must have at least two properties:

 

  • type: A string identifying the model type.  By default, use the class name.  In this case “Contact”.
  • guid: A unique identifier.  This will be used to auto-merge/update records in the future.

Here is an example of some JSON data:


var records = [
  { type: "Contact", firstName: "Charles", lastName: "Jolley", guid: "contact-1", favoriteNumber: "3" }
];

 

All models are kept in an in-memory database called the Store.  To add records to the Store, you just get these data hashes from your server in whatever way you like and add them to the store like so:

SC.Store.updateRecords(records);

records should be an array of one or more data hashes.  Note that you can call this method as often as you need.  If you pass in data hashes with a type/guid matching an existing record, then the hash will simply update the record.  Otherwise, one new record instance will be found for each item.

If you want to try the following examples without having to create a new app, you can simply add some sample records to the fixtures file created in Step 1 above.  These fixtures will be auto-loaded into the Store on app load.

To Get Records

In your app, you can retrieve some records from the store using finder functions.  This call will find all the contacts in the store (this does not contact your server, it just uses whatever is in the local datastore.  You should load your records into the store first.):

var recs = Contacts.Contact.findAll();

To Edit Records

Just set and get properties on them.  If the properties are string type, you don’t even need to declare them:


var rec = Contacts.Contact.findAll()[0];
rec.set(’firstName’, ‘Joe’); // changes the firstName to Joe.

If you have a property that is not a string but some other type, you can add a line to the Contact class declaring the type:


Contacts.Contact = SC.Record.extend({
  favoriteNumberType: Number
});

Now when you get/set the favoriteNumber property, the Contact record will automatically convert it to/from a number.  This works for dates and can even work for other model objects, but that is for another tutorial.

To Save Records

You can get back out the attributes hash of a record by getting the attributes property:


var rec = Contacts.Contact.findAll().first();
var attrs = rec.get('attributes');

This will be a JSON-compliant hash that you can serialize and send back to your server in your favorite way.

Conclusion

That’s it for part 1.  There is a lot more you can do with the model layer.  As usual, the in-source docs are best and can be views on the doc viewer page.

 

13 Responses to “30-second Tutorial on Models”

  1. Very nice introduction to models. Can you go further with server interactions ? It would be great to see an example of a model interacting with a remote server to retrieve, update and save records.


  2. Me too , I would like please to know how to interact with the server ;=)

    Really nice framework by the way,

    Antoine


  3. I may misunderstand, but above when you say

    A string identifying the model type.
    By default, use the class name. In
    this case “Model”.

    Do you actually mean, ‘In this case “Contact”.’?


  4. @Ron: thanks fixed.

    @antoine: working on it. thanks for the feedback.


  5. [...] Models Tutorial [...]


  6. Is there any way to determine which records were modified?


  7. Started looking at sproutcore today. I really like it!
    Looking forward to some more documentation. Especially more information on server interaction.


  8. Thank you for the article.
    I too would love to see an example that would talk to the back-end.
    Googling around I came across a project called jBatti which is an ORM implementation for JavaScript. I think we are seeing JavaScript replacing other languages all the way down to the server. We live in interesting times.


  9. Is there a special trick to declaring properties which are relationships? We are having trouble binding up values beyond the first record encountered - that is, through a relationship - I’m thinking that it’s not working because we have failed to declare the type for that property.


  10. Kenny: Yes let’s say you have two records: AddressBook.Contact and AddressBook.Address and you want a Contact to have an Address. you would do:

    AddressBook.Contact = SC.Record.extend({

    addressType: “AddressBook.Address”

    });

    With this design, SproutCore will expect the address property you store in the attributes hash to be the *guid* of the Address record. Then you can do:

    contact.get(’address’) and it will return an address.


  11. Awesome. I can even make Contact.address an array like [101,102], and it will find them! Now I have another problem: I tried to add a third text_field_view to the Contacts example and bound it up to “Contacts.detailController.address.street”, but it comes up empty. When I bind it up to just “Contacts.detailController.address”, I get “Record({ guid=101 })”, so everything seems to be working fine up to that point.


  12. That sound very good. Please give us a complete example using with server interactions.


  13. I started playing with sproutcore about an hour ago, about half an hour of this time was trying to figure out why the second command on this page kept on bringing up the help text for the “sc-gen model” command.

    Assuming I understand correctly, I think it should have brought up a “directory not found” error, and that in fact the project_name in the first command should actually be “contacts” - because when i changed contacts/contact to hello_world/contact - then I could get my model created. since no one else mentions this, I assuming (again) that everyone else understood “ah yes the project is actually called contacts, and the sc-gen command will assume that this directory exists”. Other than that sproutcore has worked nicely, and should help me out with some projects, thanks for making it Charles.


Discussion Area - Leave a Comment