Find file
Fetching contributors…
Cannot retrieve contributors at this time
467 lines (310 sloc) 26 KB

Getting Started

After reading this guide, you will be able to:

  • Use SproutCore’s templating support to describe the appearance of your application.
  • Delegate handling of user events with views.
  • Use bindings to update views when your models change.

You will learn all of this by building a real Todo list application from the ground up using SproutCore.

endprologue.

Following Along

You can see the finished source code for this application on Github. To see it in action, click here.

There is also a screencast available on Vimeo.

Installing SproutCore

This guide assumes you have already installed SproutCore. If you have not, please install it now.

WARNING: This tutorial requires the 1.6.0 beta. The Windows and Mac installers are both for the beta version, but if you install via RubyGems, you’ll need to use gem install sproutcore --pre to get the beta.

Generate Your New Application

First, generate your new HTML-based application.

$ sc-init todos —template

This will create several files needed for your application, inside the apps/todos directory.

  • apps/
    • todos/
      • todos.js – The JavaScript file that will define your models, views, and controllers.
      • resources/
        • templates/ – Place all Handlebars templates here.
          • todos.handlebars – The main template for the application.
        • images/ – Place all images here.
        • stylesheets/ – Place all stylesheets here.
          • todos.css – The main stylesheet for the application.
      • tests/
  • Buildfile – Tells SproutCore how your application should be built. Usually, you can just use the defaults provided.
  • README – The description for the project.

Go ahead and open todos.js now. You should see the following code:

Todos = SC.Application.create();

SC.ready(function() {
Todos.mainPane = SC.TemplatePane.append({
layerId: “todos”,
templateName: “todos”
});
});

This code creates a namespace for your application (called Todos), then appends a new pane. A pane is responsible for event delegation and placing your templates into the DOM, but you’ll learn more about that later.

INFO: If you pass a camelcase name to sc-init, such as ToDos — notice the uppercase ‘D’ —, the namespace would instead be ToDos and the directories would be named with underscores (i.e. apps/to_dos)

Defining Your Model

In this tutorial, we want to create a list for managing todos. Users should be able to create a new todo with a specific task, then check it off once it’s done.

Let’s define our model as a new subclass of SC.Object:

Todos = SC.Application.create();

Todos.Todo = SC.Object.extend({
title: null,
isDone: false
});

SC.ready(function() {
Todos.mainPane = SC.TemplatePane.append({
layerId: ‘todos’,
templateName: ‘todos’
});
});

NOTE: Make sure you insert the new code after the Todos object is created.

We’ve now defined a class with two properties: title, a String, and isDone, a Boolean.

Managing the Model Using a Controller

Now that we know what our data looks like, let’s create a controller to manage it. Since we want to maintain an ordered list of todos, we’ll use an instance of SC.ArrayController.

// at the end of the file

Todos.todoListController = SC.ArrayController.create({
// Initialize the array controller with an empty array.
content: []
});

INFO: In MVC frameworks, like SproutCore, the controller layer bridges the model layer, which is only concerned with a pure-data representation of objects, and the view layer, which is only concerned with representing those objects.

Now we have an array controller with no content. Let’s add a method to create a new todo:

// updating previous code

Todos.todoListController = SC.ArrayController.create({
// Initialize the array controller with an empty array.
content: [],

// Creates a new todo with the passed title, then adds it // to the array. createTodo: function(title) { var todo = Todos.Todo.create({ title: title }); this.pushObject(todo); }

});

NOTE: SC.ArrayController acts as a proxy onto its content Array. SproutCore will propagate any modifications made to the ArrayController to the content Array.

Creating New Todos with a Text Field

NOTE: We’ve provided a simple stylesheet to give the application some style. At this point, you should download the CSS and replace the empty file that sc-init generated for us at apps/todos/resources/stylesheets/todos.css.

We’ve got our model and controller set up, so let’s move on to the fun part: creating the interface for our users. The first step is to create a text field into which the user types the name of their todo. SproutCore’s TemplateView uses Handlebars templates to quickly define the application’s interface. While Handlebars makes it easier to markup HTML quickly, you’ll see that it has been extended to take advantage of SproutCore with very little additional effort.

To start building our views, let’s open resources/templates/todos.handlebars. You’ll see that the initialization pre-populated the file with a snippet of HTML:

Welcome to SproutCore!

Go ahead and replace that with:

Todos

NOTE: For more information about using Handlebars, visit the Handlebars website. To learn more about using Handlebars with SproutCore, make sure to check out the Using Handlebars Template guide.

Now that we’ve got model, view, and controller represented, it’s time to open the app in our browser and see how it looks.

During the development process, sc-server makes it easy to test your application. Just run the following inside of your project directory:

$ sc-server

Starting server at http://0.0.0.0:4020 in debug mode
To quit sc-server, press Control-C
>> Thin web server (v1.2.1 codename Bat-Shit Crazy)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:4020, CTRL+C to stop

Open your web browser and navigate to http://localhost:4020/todos. You should see your application load. Once you’ve verified that the application is up and running, it’s time to tell SproutCore how to handle events for your <input> tag. When the user types in the field and presses return, we will create a new Todo and have it inserted into the content of the array controller.

NOTE: In SproutCore, view objects are responsible for updating the DOM and handling events. Among other things, this allows us to buffer changes to the DOM for maximum performance and to support generic cross-platform event handling. Whenever you want to display dynamic content or handle events, you will use a view object.

// before SC.ready

Todos.CreateTodoView = SC.TextField.extend({
insertNewline: function() {
var value = this.get(‘value’);

if (value) { Todos.todoListController.createTodo(value); this.set(‘value’, ’’); } }

});

Since CreateTodoView contains a text field, we create a subclass of SC.TextField, which provides several conveniences for working with text fields. For example, you can access the value property and respond to higher level events such as insertNewline, when the user presses return.

Now that we have defined our view, we need to attach it to HTML in our Handlebars template. Wrap the <input> like so:

Todos

{{#view Todos.CreateTodoView}}

{{/view}}

#view is a Handlebars block helper that assigns a SC.TemplateView to a section of HTML. This means that the behavior described in the specified view, such as event handling, will get associated with the HTML inside the block.

Now that we have an interface to create new todos, let’s create the interface to display them. We’ll use the Handlebars #collection helper to display a list of items. #collection will create an instance of SC.TemplateCollectionView that renders every item in its underlying Array using the enclosed HTML.

{{#collection SC.TemplateCollectionView ¬
contentBinding=“Todos.todoListController”}}
{{content.title}}
{{/collection}}

WARNING: We are using a continuation character (¬) to indicate that the lines should be entered unbroken.

Notice that we’ve also told the collection to bind its content property to our todoListController. For every item in the array controller, the collection view will create a new child view that renders the {{content.title}} template.

NOTE: You set up bindings by creating a property whose name ends in Binding. In this case, we bind Todos.todoListController to the collection view’s content property. When one end of a binding changes, SproutCore will automatically update the other end.

This is a good time to visit http://localhost:4020/todos in your browser (or reload if you still have it open). It should look the same as before. Type a todo into the text field and hit return.

Look at that! As soon as we create a new todo and insert it into the array controller, the view updates automatically.

You’ve now seen a little bit of the power of SproutCore. By using SproutCore’s bindings to describe the relationship between your data and your views, you were able to change the data layer and let SproutCore do the hard work of updating the view layer for you.

INFO: This is actually a core concept in SproutCore, not just something that demos well. SproutCore’s binding system is designed with the view system in mind, which makes it easy to work directly with your data and not need to worry about manually keeping your view layer in sync. You will see this concept over and over again in the rest of this tutorial and in other guides.

Getting Things Done

We now have the ability to add todos, but no way to mark them as done. Before the frustration of a never-ending todo list gets the better of us, let’s add the ability to mark todos complete.

The first thing we need to do is add a checkbox to each todo list item. As was mentioned earlier, if we want to handle events, such as user input, we need a view to manage that portion of HTML. In this case, we are adding a checkbox and want to be notified whenever the value of the checkbox is changed by the user. Remember that we can assign views using the #view helper and provide the HTML content for the assigned view in our template. However, we can also reference views that provide their own HTML content using the view helper — notice the lack of the #. For instance, we may want to create a complex view that will be used repeatedly and don’t want to have to update all the templates whenever it needs to be updated. Here’s what the todo list looks like after updating it in todos.handlebars:

{{#collection SC.TemplateCollectionView ¬
contentBinding=“Todos.todoListController”}}
{{view Todos.MarkDoneView}}
{{/collection}}

Now let’s implement the Todos.MarkDoneView, which we just referenced. Since our view implements a checkbox, we will subclass the SC.Checkbox control. This gives the view a value property that reflects the value in the DOM, as well as a title property that displays a label for the checkbox.

INFO: Under the hood, SproutCore binds an event handler to the change event and updates value when the event occurs. This may change as needed for browser compatibility, but working with a SproutCore property insulates you from those concerns.

For every item in its underlying Array, SC.TemplateCollectionView will create a new child view whose content property contains the object the view should represent. In our case, there will be a child view for each todo, and each will have a content property set to a corresponding Todo object.

This makes it easy to bind the properties of the checkbox to the properties of the Todo object we’re representing. In this case, we bind value to isDone and title to title, so that when one changes, the other changes automatically. Let’s tie it all together:

// before SC.ready

Todos.MarkDoneView = SC.Checkbox.extend({
titleBinding: ‘.parentView.content.title’,
valueBinding: ‘.parentView.content.isDone’
});

Before you reload the browser to see the new checkbox todo list items, the stylesheet we provided includes a CSS class meant to give completed todos a unique look, so lets also bind the class of each item to the object’s isDone property.

We’ll use a property on the collection helper to set up this binding:

{{#collection SC.TemplateCollectionView ¬
contentBinding=“Todos.todoListController” ¬
itemClassBinding=“content.isDone”}}
{{view Todos.MarkDoneView}}
{{/collection}}

This property defines a binding on each of the item views. Each item will get the class is-done if its associated content object’s isDone property is true. SproutCore will automatically dasherize property names into class names.

NOTE: All views have a number of properties, including id, class, and classBinding. The collection helper allows you to prefix any of those properties with item, which will then apply them to each of the child item views. For instance, if you use the itemClass property on a collection, each item will get that class.

Now reload your application in the browser and try it out. As soon as you click a todo’s checkbox, the text will become crossed out. Keep in mind you didn’t need to update any views when marking the Todo as done, bindings did it for you. If a different part of the app changes the Todo item’s isDone property, your list item would automatically update without any more work on your part.

The More You Know

We can now create todos and mark them as being complete. While 76% of all statistics are made up, let’s see if we can display more accurate information from the data we have. At the top of our list, let’s display the number of todos remaining. Open todos.handlebars and insert this new view:

{{#view Todos.StatsView id="stats"}}
{{displayRemaining}} remaining
{{/view}}

Handlebars expressions, like {{displayRemaining}}, allows us to automatically update the DOM when a property on our view changes. In this case, we’re saying that the content of the Todos.StatsView should be bound to the value of the view’s displayRemaining property. As with the other bindings, this will be updated for us automatically whenever the value changes.

Let’s go ahead and implement that view in todos.js now:

// before SC.ready

Todos.StatsView = SC.TemplateView.extend({
remainingBinding: ‘Todos.todoListController.remaining’,

displayRemaining: function() { var remaining = this.get(‘remaining’); return remaining + (remaining === 1 ? " item" : " items"); }.property(‘remaining’)

});

displayRemaining contains a pluralized string, based on the number of remaining todos. Here is another core piece of SproutCore in action, this one called a computed property. Computed properties are properties whose value is determined by running a function. For example, if remaining equals 1, displayRemaining will contain the string "1 item".

We say that displayRemaining depends on remaining because it requires another value to generate its own value. We list these dependent keys inside the property() declaration.

We’ve also bound the view’s remaining property to the todoListController‘s remaining property. This means that, because of the dependency chain we’ve described, if Todos.todoListController.remaining changes, displayRemaining will automatically update.

When we have information that views need but is based on aggregate information about our models, the array controller is a good place to put it. Let’s add a new computed property to todoListController in todos.js:

// updating previous code

Todos.todoListController = SC.ArrayController.create({

// … remaining: function() { return this.filterProperty(‘isDone’, false).get(‘length’); }.property(‘@each.isDone’)

});

Here, we specify our dependent key using @each. This allows us to depend on properties of the array’s items. In this case, we want to update the remaining property any time isDone changes on a Todo.

NOTE: The @each property also updates when an item is added or removed.

It’s important to declare dependent keys because SproutCore uses this information to know when to update bindings. In our case, our StatsView updates any time todoListController’s remaining property changes.

Here’s how it all fits together:

INFO: As we build up our application, we create declarative links between objects. These links describe how application state flows from the model layer to the HTML in the presentation layer.

Clearing Completed Todos

As we populate our list with todos, we may want to periodically clear out those we’ve completed. As you have learned, we will want to make that change to the todoListController, and let SproutCore automatically propagate those changes to the DOM.

Let’s add a new clearCompletedTodos method to the controller.

// updating existing code

Todos.todoListController = SC.ArrayController.create({

// … clearCompletedTodos: function() { this.filterProperty(‘isDone’, true).forEach(this.removeObject, this); }

});

Next, let’s add a button to our template. Open todos.handlebars and add a button inside the HTML for StatsView as shown here:

{{#view Todos.StatsView id="stats"}}
{{#view SC.Button classBinding=“isActive” ¬
target=“Todos.todoListController” ¬
action="clearCompletedTodos"}}
Clear Completed Todos
{{/view}}
{{displayRemaining}} remaining.
{{/view}}

We’ve defined an instance of SC.Button, which calls a method on an object when it is clicked. In this case we’ve told the button to call the clearCompletedTodos method (its action) on the Todos.todoListController object (its target).

We’ve also told it to add an is-active class to the view when it is clicked or tapped. Every SC.Button has an isActive property that will be true when it is in the process of being clicked. This allows us to display a visual cue to the user that they have hit the right target.

Go back to your browser and try it out. Add some todos, then mark them done and clear them. Because we previously bound the visual list to the todoListController, making a change through new means has the expected effect.

Marking All as Done

Let’s say you’ve decided to actually get all of your work done. Wouldn’t it be nice to have a way to easily mark every todo as complete?

It turns out that, due to our application’s declarative nature, all the hard work is already done. We just need a way to mark every Todo complete.

Let’s first create a new computed property on our controller that describes whether or not every todo is done. It might look something like this:

// updating existing code

Todos.todoListController = SC.ArrayController.create({

// … allAreDone: function() { return this.get(‘length’) && this.everyProperty(‘isDone’, true); }.property(‘@each.isDone’)

});

INFO: SproutCore has many enumerable helpers. everyProperty(‘isDone’, true) returns true if every item in the array has an isDone property that evaluates to true. You can find out more in the Enumerables guide.

Next, we’ll create a checkbox view to mark all items complete and bind its value to the controller’s property:

{{view SC.Checkbox class=“mark-all-done” ¬
title=“Mark All as Done” ¬
valueBinding=“Todos.todoListController.allAreDone”}}

If you were to reload your browser and use the app now, you’d notice that clicking all of the checkboxes of your todos will cause the “Mark All as Done” checkbox to become checked. However, it doesn’t work in the other direction: clicking “Mark All as Done” has no effect.

So far, our computed properties have described how to calculate a value from dependent properties. However, in this case, we want to accept a new value, and update dependent properties to reflect it. Lets update our allAreDone computed property to also accept a value.

// updating existing code

Todos.todoListController = SC.ArrayController.create({

// … allAreDone: function(key, value) { if (value !== undefined) { this.setEach(‘isDone’, value); return value; } else { return this.get(‘length’) && this.everyProperty(‘isDone’, true); } }.property(‘@each.isDone’)

});

When you set a computed property, your computed property function is called with the property key as the first parameter and the new value as the second. To determine if SproutCore is asking for the value or trying to set it, we examine the value parameter. If it is defined, we iterate through each Todo and set its isDone property to the new value.

Because bindings are bi-directional, SproutCore will set allAreDone to true when the user clicks the “Mark All as Done” checkbox. Conversely, unchecking it will make SproutCore set allAreDone to false, unchecking all todos.

Reload the app and add some todos. Click “Mark All as Done”. Wow! Each of the individual check boxes gets checked off. If you uncheck one of them, the “Mark All as Done” checkbox un-checks itself.

INFO: When you use SproutCore, as you scale your UI, you never need to wonder whether a new feature will work consistently with parts of the UI you already implemented. Since you build your view layer to simply reflect the state of your models, you can make changes however you want and see them update automatically.

Mobile Specific Styles

At this point, we actually have the app fully functional on all modern mobile devices. Let’s optimize the experience for all of the different screen sizes we might encounter. Download the CSS for mobile and save it as apps/todos/resources/stylesheets/todos_mobile.css. Now load your app on a mobile device and you should see the same app, but styled properly for mobile devices and responding to touch events.

NOTE: The SproutCore development server will be available on your local network at your machine’s IP address. For example, you might visit http://192.168.1.1:4020/todos.

Resources

Now that you have finished the first part of the Getting Started tutorial, you will want to acquaint yourself with the resources available to the SproutCore community.

Continue On

Now that you’ve built a basic SproutCore app, continue on to the next part of this tutorial to learn about working with SproutCore’s model layer.

Changelog

  • March 1, 2011: initial version by Tom Dale and Yehuda Katz
  • March 2, 2011: fixed formmating and added paths to filenames by Topher Fangio and Peter Wagenet
  • March 22, 2011: cleaned up demo based on new features by Yehuda Katz
  • April 11, 2011: consistently use view classes and extend, update to reflect better Handlebars integration by Yehuda Katz and Tom Dale
  • May 6, 2011: clarifications, minor inconsistency fixes, updated CSS for older browsers, plus new mobile section by Tyler Keating
  • May 9, 2011: update for recent changes in SproutCore 1.6 by Tom Dale and Yehuda Katz