Hello World Tutorial 3: Adding Buttons
In the last tutorial you installed SproutCore then added your first view and controller. Now we are going to add a button and some interactivity to your page.
One of the things that makes working with SproutCore fun is that it lets you break your app into pieces. Other parts of the app are bound together using bindings and observers and will update automatically so you don’t have to worry about them. Instead you can focus just on one part at a time to get it just right.
In our current example, we have a controller with a greeting property that is bound to a label view displaying the greeting. Now we want to add a method that will toggle the greeting between two different states. So let’s start by adding the method to do this.
Step 1. Add an Action to the Controller
Adding a new method to an object is really easy in SproutCore. You don’t need to create a new subclass or anything like that. Just add a new method to the object, just like you might add a property. In fact, in your app controller, add a comma at the end of the property and add the following:
toggleGreeting: function() {
var currentGreeting = this.get('greeting');
var newGreeting = (currentGreeting === 'Hello World!') ? 'I am on SproutCore!' : 'Hello World!' ;
this.set('greeting', newGreeting);
}
That’s it. You can refresh the page in Firefox and open your console in Firebug again if you want and type:
HelloWorld.appController.toggleGreeting();
and watch the label view change. Of course, when you write full applications with SproutCore, you may not always know all the objects that are bound to properties on your object. The important thing is you can just focus on fixing the state of each controller or model object in your system and generally the rest of the app will take care of itself.
Now that we have an action method, let’s add a button to toggle it.
Step 2. Add a Button View
Back in your body.rhtml, add the following line just above the label view:
<%= button_view :toggle_button, :title => 'Change Title', :action => 'HelloWorld.appController.toggleGreeting' %>
Hopefully the text here is pretty self explanatory. The action is the method to call when you click the button. Reload the web browser and click the button to see what happens.
So far you’ve built a basic view, a controller, setup a binding and an action. There is one more key concept to cover in this brief tour of SproutCore: observers. We’ll cover that in the next tutorial.