Key Value Coding and Key Value Observing (KVC & KVO)

by Evin

We will look at some structure to using Sproutcore’s Key Value Coding (KVC) and Key Value Observing (KVO) framework. KVC and KVO is a direct port from the Cocoa framework, but it is better in Sproutcore because it is a foundational construct rather than an addition as it is in the Cocoa Framework. This is where most of the power of Sproutcore can be seen and there is a good paradigm that should be used to harness most of this power. We will start with a short discussion on what KVC and KVO is:

Key Value Coding (KVC)

Key Value Coding is where to ‘get’ or ‘set’ properties on an object in the following format:

  myModel.get('myProperty'); 
  myModel.set('myProperty', 'myValue');

Access to all properties **NEEDS** to be done in this way to invoke the KVC and KVO structure in Sproutcore. Only violate this in very narrow ways and only because you know what you are doing.

Key Value Observing (KVO)

Key Value Observing (KVO) is usually harnessed through the view rhtml object by binding the values of the views to some things:

  titleBinding: 'App.modelController.name'

It can also be done in the code when you set the binding structures in the controllers.

Using KVC and KVO

I will start with a picture:

This is a representation of what you should use. When in a View and you change something you drive changes using KVC ‘set’ functions through the View to the Controller and then through to the Model. Then the changes *bounce* back up using the KVO that you have set up. This provides a great way to systemically make changes in an orderly manner. There is a great discussion on KVC and KVO
on the Sproutcore Wiki by Erich Ocean (onitunes)

This entry was posted on Wednesday, November 26th, 2008 at 3:43 pm and is filed under Best Practices. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Key Value Coding and Key Value Observing (KVC & KVO)”

  1. Charles Jolley Says:

    Great new website so far!

    I wanted to mention a rule I usually recommend people follow is to begin all properties that do not use KVO with an underscore. Thus if a property name does not have an underscore at the front, you know it MUST use get()/set(). If it does have an underscore, you MUST NOT use it.

    Keep up the great work!

Leave a Reply