Skip to content

Hello World Tutorial 3: Adding Buttons

juanpin edited this page Sep 13, 2010 · 18 revisions

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 main_page.js, add a buttonView to your childViews as follows:

childViews: 'labelView buttonView'.w()

then declare your button view, add a comma after the labelView declaration and then insert:

buttonView: SC.ButtonView.design({
      layout: { centerX: 0, centerY: 20, width: 250, height: 18 },
      title: "Change Title",
      action: "toggleGreeting",
      target: "HelloWorld.appController"
    })

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.

Go to Hello World Tutorial 4: Observers » Hello World Tutorial 4: Observers

Comments

edit this page to add comments here