Introduction to SproutCore Part Two

    The first part of the SproutCore tutorial talked about creating a simple application.
    It's time to deepen your knowledge and deal with Models in SproutCore.

    After reading this manual, you will be able to:

    • Describe models using SC.Record.
    • Manage models with SC.Store.
    • Load initial data into storage.
    • Send storage queries using SC.Query.


    1 Preparing the application



    The first part of this tutorial explained how to build a simple Todo-List application.
    Now you know how to describe models, views, and controllers, and how to define their interaction using bindings.
    However, we did not have the ability to store information between page updates.

    One way to implement this is to use SproutCore's data warehouse to manage your records.
    The SC.Store instance is responsible for managing the life cycle of the records.
    SC.Store uses SC.DataSource to process data downloaded from the server and to prepare it for sending back to the server.

    If you still have the application from the first part of this guide, use it.
    If not, you can download it from GitHub.

    In order to use the storage, you must include it in the list of modules used for our application.
    Used modules are specified in the Buildfile in the config section.

    config :all, :required => ["sproutcore/core_foundation", "sproutcore/datastore"], :theme => "sproutcore/empty_theme"
    


    2 Model Definition



    In the last lesson, we defined the model as a subclass of SC.Object, redefining it using SC.Record.
    Change the code in the apps / todos / todos.js file:

    Todos.Todo = SC.Record.extend({
      title: SC.Record.attr(String),
      isDone: SC.Record.attr(Boolean, { defaultValue: NO })
    });
    


    Now we use SC.Record as the base class for the model. We also defined the attributes of the model and their types.
    Title is now always converted to a string, and isDone to a Boolean variable. Also, isDone now defaults to false
    unless otherwise specified.

    3 Creating a static source dataset



    The easiest way to start development without connecting to the backend server is to use a static set of source data.
    A static collection is an array of data hashes that represent each record.
    Let's create such a set, for this we add the following code to the apps / todos / todos.js file after the model description:
    Todos.Todo.FIXTURES = [
        { "guid": "todo-1",
          "title": "Build my first SproutCore app",
          "isDone": false },
        { "guid": "todo-2",
          "title": "Build a really awesome SproutCore app",
          "isDone": false },
        { "guid": "todo-3",
          "title": "Next, the world!",
          "isDone": false }
    ];
    


    Now we have a model and initial data, but if you run the application, then no changes are visible.
    The fact is that SC.Store is responsible for loading the data. Add code to the controller that creates the data warehouse for our application.
    In the apps / todos / todos.js file, write the following:

    // создадим хранилище во время создания пространства имен приложения
    Todos = SC.Application.create({
      store: SC.Store.create().from(SC.Record.fixtures)
    });
    


    We have created a data warehouse for the application. For now, we use static source data, but then we can
    specify the real data source as an argument to the from () function.

    Let's check how our application works. Run the sc-server command and open http: // localhost: 4020 / todos in the browser .
    Now in the javascript console of our browser we will write the following commands:

    records = Todos.store.find(Todos.Todo)
    records.objectAt(0).get('title')
    


    We get the result:
    // => "Build my first SproutCore app"
    


    We simply called the find () method of our repository, which returns all records as an instance of the SC.RecordArray class.
    If you create a new record, it will automatically be added to the repository, also when the record is destroyed, it will disappear from the repository.

    4 Controller and storage bundle



    Now we can use the storage in the controller of our application. To do this, set the content property of the Todos.todoListController object to the
    value returned by the find () function of the store. This can be done in the callback of the SC.ready () function.

    Change the code in the apps / todos / todos.js file to the following:
    SC.ready(function() {
      Todos.mainPane = SC.TemplatePane.append({
        layerId: 'todos',
        templateName: 'todos'
      });
      var todos = Todos.store.find(Todos.Todo);
      Todos.todoListController.set('content', todos);
    });
    


    If we refresh the page of our application, it is clear that the initial data that we uploaded to the repository is displayed.
    Next, we rewrite the function for creating new tasks in the apps / todos / todos.js file to the following:

    createTodo: function(title) {
      Todos.store.createRecord(Todos.Todo, { title: title });
    },
    


    And finally, change the task deletion function in the apps / todos / todos.js file:

    Todos.todoListController = SC.ArrayController.create({
      // ...
      clearCompletedTodos: function(){
        this.filterProperty('isDone', true).forEach( function(item) {
          item.destroy();
        });
      },
      // ...
    )};
    


    Now our application is fully functional and uses the data warehouse for its work.
    The storage connects to the backend server without any problems through JSON messaging.

    Original article

    Also popular now: