Blame platform-demos/pt_BR/03_getting_the_signal.js.page

Packit 1470ea
Packit 1470ea
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:xi="http://www.w3.org/2001/XInclude" type="topic" style="task" id="03_getting_the_signal.js" xml:lang="pt-BR">
Packit 1470ea
  <info>
Packit 1470ea
    <link type="guide" xref="beginner.js#tutorials"/>
Packit 1470ea
    <link type="seealso" xref="button.js"/>
Packit 1470ea
    <link type="seealso" xref="entry.js"/>
Packit 1470ea
    <link type="seealso" xref="radiobutton.js"/>
Packit 1470ea
    <link type="seealso" xref="switch.js"/>
Packit 1470ea
    <revision version="0.1" date="2012-08-12" status="draft"/>
Packit 1470ea
Packit 1470ea
    <credit type="author copyright">
Packit 1470ea
      <name>Taryn Fox</name>
Packit 1470ea
      <email its:translate="no">jewelfox@fursona.net</email>
Packit 1470ea
      <years>2012</years>
Packit 1470ea
    </credit>
Packit 1470ea
Packit 1470ea
    <desc>Crie Buttons e outros widgets que fazem coisas quando clicados.</desc>
Packit 1470ea
  
Packit 1470ea
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
Packit 1470ea
      <mal:name>Rafael Ferreira</mal:name>
Packit 1470ea
      <mal:email>rafael.f.f1@gmail.com</mal:email>
Packit 1470ea
      <mal:years>2013</mal:years>
Packit 1470ea
    </mal:credit>
Packit 1470ea
  </info>
Packit 1470ea
Packit 1470ea
  <title>3. Obtendo o Signal</title>
Packit 1470ea
  <synopsis>
Packit 1470ea
    

No último tutorial, nós aprendemos como criar widgets tipo Labels (rótulos), Images (imagens) e Buttons (botões). Aqui, nós vamos aprender como fazer para Buttons e outros widgets de entrada realmente fazer as coisas, escrevendo funções que lidam com os sinais que elas enviam quando elas são clicadas ou recebem interação.

Packit 1470ea
  </synopsis>
Packit 1470ea
Packit 1470ea
  <links type="section"/>
Packit 1470ea
Packit 1470ea
  <section id="application">
Packit 1470ea
    <title>Um aplicativo básico</title>
Packit 1470ea
    

No GNOME, widgets com os quais você pode interagir, como Buttons e Switches, enviam sinais quando são clicados ou ativados. Um Button, por exemplo, envia o sinal de "clicado" quando alguém clica nele. Quando isto acontece, o GNOME procura a parte do código que diz o que deve ser feito.

Packit 1470ea
    

Como nós vamos escrever esse código? Conectando aquele sinal de "clicado" do Button a uma função de chamada, que é uma função que você escreve apenas para lidar com esse sinal. Então, quando você aplica aquele sinal, a função conectada a ele será executada.

Packit 1470ea
    

Aqui está um exemplo extremamente básico:

Packit 1470ea
Packit 1470ea
    <media type="image" mime="image/png" src="media/03_jssignal_01.png"/>
Packit 1470ea
Packit 1470ea
    

Esse ApplicationWindow possui um Button e um Label, organizados em uma Grid. Quando o Button é clicado, uma variável que mantém o número de cookies é incrementada em 1 e o Label que mostra quantos cookies existem será atualizado.

Packit 1470ea
    <note style="tip">

Os cookies neste exemplo não são os mesmos que aqueles que você obtém de sites, que armazenam a informação da sua sessão e podem manter rastro de quais sites você visitou. Eles são apenas biscoitos imaginários. Você pode preparar alguns de verdade, se quiser.

</note>
Packit 1470ea
    

Aqui está o código básico, padrão que vai na inicialização do aplicativo, antes de começar a criação da janela e widgets. Além do aplicativo ter um nome único, a maior alteração em relação ao padrão é que nós criamos uma variável global bem perto do começo, para manter o número de cookies.

Packit 1470ea
    
Packit 1470ea
#!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
imports.gi.versions.Gtk = '3.0';
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
Packit 1470ea
// We start out with 0 cookies
Packit 1470ea
var cookies = 0;
Packit 1470ea
Packit 1470ea
class GettingTheSignal {
Packit 1470ea
    // Create the application itself
Packit 1470ea
    constructor() {
Packit 1470ea
        this.application = new Gtk.Application();
Packit 1470ea
Packit 1470ea
        // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
        this.application.connect('activate', this._onActivate.bind(this));
Packit 1470ea
        this.application.connect('startup', this._onStartup.bind(this));
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup() {
Packit 1470ea
        this._buildUI ();
Packit 1470ea
    }
Packit 1470ea
]]>
Packit 1470ea
    

Take a look at the part that uses our application's connect method and bind, to connect its activate and startup signals to the functions that present the window and build the UI. We're going to do the same thing with our Button when we get to it, except that we're going to connect its "clicked" signal instead.

Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="button">
Packit 1470ea
    <title>Clicando no botão</title>
Packit 1470ea
Packit 1470ea
    

Como de costume, não colocamos todo o código para criar um Button e outros widgets dentro da função _buildUI, a qual é chamada quando o aplicativo é iniciado.

Packit 1470ea
    
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI() {
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Primeiro, nós criamos a janela em si:

Packit 1470ea
    
Packit 1470ea
        // Cria a janela do aplicativo
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 200,
Packit 1470ea
            default_width: 400,
Packit 1470ea
            title: "Clique no botão para obter um cookie!"});
Packit 1470ea
Packit 1470ea
    

Note que nós definimos as propriedades de seus default_height e default_width. Estes permite que nós controlemos o quão alto e largo o ApplicationWindow será, em pixels.

Packit 1470ea
    

A seguir, nós vamos criar o Label que nos mostra o número de cookies. Nós podemos usar as variáveis de cookies como parte da propriedade do rótulo do Label.

Packit 1470ea
    
Packit 1470ea
        // Cria o rótulo
Packit 1470ea
        this._cookieLabel = new Gtk.Label ({
Packit 1470ea
            label: "Número de cookies: " + cookies });
Packit 1470ea
Packit 1470ea
Packit 1470ea
    

Agora nós vamos criar o Button. Nós defimos a propriedade do rótulo para mostrar o texto que nós queremos no Button e nós conectamos seu sinal de "clicado" a uma função chamada _getACookie, a qual nós vamos escrever após nós terminarmos a construção da interface gráfica do nosso aplicativo.

Packit 1470ea
    
Packit 1470ea
        // Create the cookie button
Packit 1470ea
        this._cookieButton = new Gtk.Button ({ label: "Get a cookie" });
Packit 1470ea
Packit 1470ea
        // Connect the cookie button to the function that handles clicking it
Packit 1470ea
        this._cookieButton.connect ('clicked', this._getACookie.bind(this));
Packit 1470ea
]]>
Packit 1470ea
    

Finalmente, nós criamos uma Grid, anexamos os Label e Button a ela e adicionamos-na à janela e informamos à janela para mostrar a si e a seu conteúdo. Isso é tudo que nós precisamos dentro da função _buildUI, de forma que nós fechamos-a com chaves, assim como uma vírgula que informa ao GNOME para continuar para a próxima função. Note que ainda que nós tenhamos escrito o código para o primeiro Label, nós ainda podemos anexá-lo à Grid de uma forma que vai colocá-lo na parte inferior.

Packit 1470ea
    
Packit 1470ea
        // Create a grid to arrange everything inside
Packit 1470ea
        this._grid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER,
Packit 1470ea
            row_spacing: 20 });
Packit 1470ea
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 1, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
]]>
Packit 1470ea
    

Agora, nós escrevemos a função _getACookie. Quando nosso Button envia seu sinal de "clicado", o código nesta função vai ser executado. Neste caso, tudo que isso faz é aumentar o número de cookies em 1 e atualizar o Label para mostrar o novo número de cookies. Nós fazemos isso usando o método set_label do Label.

Packit 1470ea
    <note style="tip">

Muitos widgets têm as mesmas propriedades e métodos. Ambos Labels e Buttons, por exemplo, tem uma propriedade de rótulo que informa que texto está dentro dele e métodos get_label e set_label que permitem a você verificar o que este texto é e alterá-lo, respectivamente. Então, se você aprende como um widget funciona, você também vai saber como outros como ele funcionam.

</note>
Packit 1470ea
    
Packit 1470ea
    _getACookie: function() {
Packit 1470ea
Packit 1470ea
        // Increase the number of cookies by 1 and update the label
Packit 1470ea
        cookies++;
Packit 1470ea
        this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
};
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Finalmente, nós executamos o aplicativo, usando o mesmo tipo de código de nosso último tutorial.

Packit 1470ea
    
Packit 1470ea
// Executa o aplicativo
Packit 1470ea
let app = new GettingTheSignal ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="switch">
Packit 1470ea
    <title>Flip the switch</title>
Packit 1470ea
    

Buttons aren't the only input widgets in our GTK+ toolbox. We can also use switches, like the one in this example. Switches don't have a label property, so we have to create a separate Label that says what it does to go next to it.

Packit 1470ea
Packit 1470ea
    <media type="image" mime="image/png" src="media/03_jssignal_02.png"/>
Packit 1470ea
Packit 1470ea
    

A Switch has two positions, Off and On. When a Switch is turned on, its text and background color change, so you can tell which position it's in.

Packit 1470ea
Packit 1470ea
    

You may have seen Switches like these in GNOME's accessibility menu, which let you turn features like large text and the on-screen keyboard on and off. In this case, the Switch controls our imaginary cookie dispenser. If the Switch is turned on, you can get cookies by clicking the "Get a cookie" Button. If it's turned off, clicking the Button won't do anything.

Packit 1470ea
    <note style="tip">

You can get to the accessibility menu by clicking on the outline of a human, near your name in the upper-right corner of the screen.

</note>
Packit 1470ea
    

Here's how we create the Switch:

Packit 1470ea
    
Packit 1470ea
        // Create the switch that controls whether or not you can win
Packit 1470ea
        this._cookieSwitch = new Gtk.Switch ();
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

We don't actually need to connect the Switch to anything. All we need to do is write an if statement in our _getACookie function, to check to see if the Switch is turned on. If we wanted to make something happen as soon as you flip the Switch, though, we would connect its notify::active signal, like so:

Packit 1470ea
    
Packit 1470ea
        // Connect the switch to the function that handles it
Packit 1470ea
        this._cookieSwitch.connect ('notify::active', this._cookieDispenser.bind(this));
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

A Switch is set to the off position by default. If we wanted the Switch to start out turned on, we would set the value of its active property to true when we create it.

Packit 1470ea
    
Packit 1470ea
        this._cookieSwitch = new Gtk.Switch ({ active: true });
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Let's just create it normally, though, and then create the Label that goes with it. We want the Switch and the Label to be kept right next to each other, so we'll create a Grid just for them, then put that Grid in our larger Grid that holds all the widgets inside it. Here's what the code looks like to create all that:

Packit 1470ea
    
Packit 1470ea
        // Create the switch that controls whether or not you can win
Packit 1470ea
        this._cookieSwitch = new Gtk.Switch ();
Packit 1470ea
Packit 1470ea
        // Create the label to go with the switch
Packit 1470ea
        this._switchLabel = new Gtk.Label ({
Packit 1470ea
            label: "Cookie dispenser" });
Packit 1470ea
Packit 1470ea
        // Create a grid for the switch and its label
Packit 1470ea
        this._switchGrid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER });
Packit 1470ea
Packit 1470ea
        // Put the switch and its label inside that grid
Packit 1470ea
        this._switchGrid.attach (this._switchLabel, 0, 0, 1, 1);
Packit 1470ea
        this._switchGrid.attach (this._cookieSwitch, 1, 0, 1, 1);
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

And now we arrange everything in the larger Grid like so.

Packit 1470ea
    
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._switchGrid, 0, 1, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Now we change the _getACookie function so that it checks to see if the cookie dispenser is turned on. We do that by using the Switch's get_active method. It returns true if the Switch is turned on, and false if the Switch is turned off.

Packit 1470ea
    <note style="tip">

When a method is used in an if statement like this, the code inside the if statement is executed if the method returns true.

</note>
Packit 1470ea
    
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Is the cookie dispenser turned on?
Packit 1470ea
        if (this._cookieSwitch.get_active()) {
Packit 1470ea
Packit 1470ea
            // Increase the number of cookies by 1 and update the label
Packit 1470ea
            cookies++;
Packit 1470ea
            this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="radio">
Packit 1470ea
    <title>Tuning the radio</title>
Packit 1470ea
Packit 1470ea
    

Another type of input widget we can use is called the RadioButton. You create them in groups, and then only one RadioButton in a group can be selected at a time. They're called RadioButtons because they work like the channel preset button in old-style car radios. The radio could only be tuned to one station at a time, so whenever you pressed one button in, another would pop back out.

Packit 1470ea
Packit 1470ea
    <media type="image" mime="image/png" src="media/03_jssignal_03.png"/>
Packit 1470ea
Packit 1470ea
    

First off, let's change our ApplicationWindow's name and increase its border_width property, so that our widgets aren't packed in too tightly. The border_width is the number of pixels between any widget and the edge of the window.

Packit 1470ea
    
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 200,
Packit 1470ea
            default_width: 400,
Packit 1470ea
            border_width: 20,
Packit 1470ea
            title: "Choose the one that says 'cookie'!"});
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

After that, we create the RadioButtons. Remember how they're created in groups? The way we do that, is we set each new RadioButton's group property to the name of another RadioButton.

Packit 1470ea
    
Packit 1470ea
        // Create the radio buttons
Packit 1470ea
        this._cookieRadio = new Gtk.RadioButton ({ label: "Cookie" });
Packit 1470ea
        this._notCookieOne = new Gtk.RadioButton ({ label: "Not cookie",
Packit 1470ea
            group: this._cookieRadio });
Packit 1470ea
        this._notCookieTwo = new Gtk.RadioButton ({ label: "Not cookie",
Packit 1470ea
            group: this._cookieRadio });
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Next, we create a Grid for the RadioButtons. Remember, we don't have to arrange things in Grids in the same order that we create them in.

Packit 1470ea
    
Packit 1470ea
        // Arrange the radio buttons in their own grid
Packit 1470ea
        this._radioGrid = new Gtk.Grid ();
Packit 1470ea
        this._radioGrid.attach (this._notCookieOne, 0, 0, 1, 1);
Packit 1470ea
        this._radioGrid.attach (this._cookieRadio, 0, 1, 1, 1);
Packit 1470ea
        this._radioGrid.attach (this._notCookieTwo, 0, 2, 1, 1);
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Normally, the RadioButton that's selected by default is the one that's the name of the group. We want the first "Not cookie" button to be selected by default, though, so we use its set_active method.

Packit 1470ea
    <note style="tip">

We could also set its active property to true when we create it.

</note>
Packit 1470ea
    
Packit 1470ea
        // Set the button that will be at the top to be active by default
Packit 1470ea
        this._notCookieOne.set_active (true);
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Now we arrange everything in our main Grid like usual ...

Packit 1470ea
    
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._radioGrid, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 1, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

And then we change our _getACookie function to test to see if the cookie button is the one that's selected.

Packit 1470ea
    
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Did you select "cookie" instead of "not cookie"?
Packit 1470ea
        if (this._cookieRadio.get_active()) {
Packit 1470ea
Packit 1470ea
            // Increase the number of cookies by 1 and update the label
Packit 1470ea
            cookies++;
Packit 1470ea
            this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="spell">
Packit 1470ea
    <title>Can you spell "cookie"?</title>
Packit 1470ea
Packit 1470ea
    

The last input widget we're going to cover is the Entry widget, which is used for single-line text entry.

Packit 1470ea
    <note style="tip">

If you need to be able to enter in a whole paragraph or more, like if you are building a text editor, you'll want to look at the much more customizable <link xref="textview.js">TextView</link> widget.

</note>
Packit 1470ea
    <media type="image" mime="image/png" src="media/03_jssignal_04.png"/>
Packit 1470ea
Packit 1470ea
    

After we change the window's name, we create the Entry widget.

Packit 1470ea
    
Packit 1470ea
        // Create the text entry field
Packit 1470ea
        this._spellCookie = new Gtk.Entry ();
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

Next, we arrange everything in the Grid ...

Packit 1470ea
    
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._spellCookie, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 1, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
    

And now we modify _getACookie's if statement again, using the Entry's get_text method to retrieve the text that you entered into it and see if you spelled "cookie" right. We don't care whether you capitalize "cookie" or not, so we use JavaScript's built-in toLowerCase method to change the Entry's text to all lower case inside the if statement.

Packit 1470ea
    <note style="tip">

An Entry widget doesn't have a label property, which is a set text string that the user can't change. (You can't normally change the label on a Button, for instance.) Instead, it has a text property, which changes to match what the user types in.

</note>
Packit 1470ea
    
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Did you spell "cookie" correctly?
Packit 1470ea
        if ((this._spellCookie.get_text()).toLowerCase() == "cookie") {
Packit 1470ea
Packit 1470ea
            // Increase the number of cookies by 1 and update the label
Packit 1470ea
            cookies++;
Packit 1470ea
            this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
]]>
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="whats_next">
Packit 1470ea
    <title>O que vem em seguida?</title>
Packit 1470ea
    

Keep reading, if you'd like to see the complete code for each version of our cookie maker application.

Packit 1470ea
    <note style="tip">

The main JavaScript tutorials page has <link xref="beginner.js#buttons">more detailed code samples</link> for each input widget, including several not covered here.

</note>
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="complete">
Packit 1470ea
    <title>Complete code samples</title>
Packit 1470ea
Packit 1470ea
    <links type="section"/>
Packit 1470ea
Packit 1470ea
    <section id="buttonsample">
Packit 1470ea
      <title>Code sample with Button</title>
Packit 1470ea
      <media type="image" mime="image/png" src="media/03_jssignal_01.png"/>
Packit 1470ea
      #!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
imports.gi.versions.Gtk = '3.0';
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
Packit 1470ea
// We start out with 0 cookies
Packit 1470ea
var cookies = 0;
Packit 1470ea
Packit 1470ea
class GettingTheSignal {
Packit 1470ea
Packit 1470ea
    // Create the application itself
Packit 1470ea
    constructor() {
Packit 1470ea
        this.application = new Gtk.Application();
Packit 1470ea
Packit 1470ea
        // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
        this.application.connect('activate', this._onActivate.bind(this));
Packit 1470ea
        this.application.connect('startup', this._onStartup.bind(this));
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup() {
Packit 1470ea
        this._buildUI();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI() {
Packit 1470ea
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 200,
Packit 1470ea
            default_width: 400,
Packit 1470ea
            title: "Click the button to get a cookie!"});
Packit 1470ea
Packit 1470ea
        // Create the label
Packit 1470ea
        this._cookieLabel = new Gtk.Label ({
Packit 1470ea
            label: "Number of cookies: " + cookies });
Packit 1470ea
Packit 1470ea
        // Create the cookie button
Packit 1470ea
        this._cookieButton = new Gtk.Button ({ label: "Get a cookie" });
Packit 1470ea
Packit 1470ea
        // Connect the cookie button to the function that handles clicking it
Packit 1470ea
        this._cookieButton.connect ('clicked', this._getACookie.bind(this));
Packit 1470ea
Packit 1470ea
        // Create a grid to arrange everything inside
Packit 1470ea
        this._grid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER,
Packit 1470ea
            row_spacing: 20 });
Packit 1470ea
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 1, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Increase the number of cookies by 1 and update the label
Packit 1470ea
        cookies++;
Packit 1470ea
        this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
};
Packit 1470ea
Packit 1470ea
// Run the application
Packit 1470ea
let app = new GettingTheSignal ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
    </section>
Packit 1470ea
Packit 1470ea
    <section id="switchsample">
Packit 1470ea
      <title>Code sample with Switch</title>
Packit 1470ea
      <media type="image" mime="image/png" src="media/03_jssignal_02.png"/>
Packit 1470ea
      #!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
imports.gi.versions.Gtk = '3.0';
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
Packit 1470ea
// We start out with 0 cookies
Packit 1470ea
var cookies = 0;
Packit 1470ea
Packit 1470ea
class GettingTheSignal {
Packit 1470ea
Packit 1470ea
    // Create the application itself
Packit 1470ea
    constructor() {
Packit 1470ea
        this.application = new Gtk.Application();
Packit 1470ea
Packit 1470ea
        // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
        this.application.connect('activate', this._onActivate.bind(this));
Packit 1470ea
        this.application.connect('startup', this._onStartup.bind(this));
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup() {
Packit 1470ea
        this._buildUI();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI() {
Packit 1470ea
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 200,
Packit 1470ea
            default_width: 400,
Packit 1470ea
            title: "Click the button to get a cookie!"});
Packit 1470ea
Packit 1470ea
        // Create the label
Packit 1470ea
        this._cookieLabel = new Gtk.Label ({
Packit 1470ea
            label: "Number of cookies: " + cookies });
Packit 1470ea
Packit 1470ea
        // Create the cookie button
Packit 1470ea
        this._cookieButton = new Gtk.Button ({
Packit 1470ea
            label: "Get a cookie" });
Packit 1470ea
Packit 1470ea
        // Connect the cookie button to the function that handles clicking it
Packit 1470ea
        this._cookieButton.connect ('clicked', this._getACookie.bind(this));
Packit 1470ea
Packit 1470ea
        // Create the switch that controls whether or not you can win
Packit 1470ea
        this._cookieSwitch = new Gtk.Switch ();
Packit 1470ea
Packit 1470ea
        // Create the label to go with the switch
Packit 1470ea
        this._switchLabel = new Gtk.Label ({
Packit 1470ea
            label: "Cookie dispenser" });
Packit 1470ea
Packit 1470ea
        // Create a grid for the switch and its label
Packit 1470ea
        this._switchGrid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER });
Packit 1470ea
Packit 1470ea
        // Put the switch and its label inside that grid
Packit 1470ea
        this._switchGrid.attach (this._switchLabel, 0, 0, 1, 1);
Packit 1470ea
        this._switchGrid.attach (this._cookieSwitch, 1, 0, 1, 1);
Packit 1470ea
Packit 1470ea
        // Create a grid to arrange everything else inside
Packit 1470ea
        this._grid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER,
Packit 1470ea
            row_spacing: 20 });
Packit 1470ea
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._switchGrid, 0, 1, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Is the cookie dispenser turned on?
Packit 1470ea
        if (this._cookieSwitch.get_active()) {
Packit 1470ea
Packit 1470ea
            // Increase the number of cookies by 1 and update the label
Packit 1470ea
            cookies++;
Packit 1470ea
            this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
};
Packit 1470ea
Packit 1470ea
// Run the application
Packit 1470ea
let app = new GettingTheSignal ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
    </section>
Packit 1470ea
Packit 1470ea
    <section id="radiobuttonsample">
Packit 1470ea
      <title>Code sample with RadioButton</title>
Packit 1470ea
      <media type="image" mime="image/png" src="media/03_jssignal_03.png"/>
Packit 1470ea
      #!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
imports.gi.versions.Gtk = '3.0';
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
Packit 1470ea
// We start out with 0 cookies
Packit 1470ea
var cookies = 0;
Packit 1470ea
Packit 1470ea
class GettingTheSignal {
Packit 1470ea
Packit 1470ea
    // Create the application itself
Packit 1470ea
    constructor() {
Packit 1470ea
        this.application = new Gtk.Application();
Packit 1470ea
Packit 1470ea
        // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
        this.application.connect('activate', this._onActivate.bind(this));
Packit 1470ea
        this.application.connect('startup', this._onStartup.bind(this));
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup() {
Packit 1470ea
        this._buildUI();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI() {
Packit 1470ea
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 200,
Packit 1470ea
            default_width: 400,
Packit 1470ea
            border_width: 20,
Packit 1470ea
            title: "Choose the one that says 'cookie'!"});
Packit 1470ea
Packit 1470ea
        // Create the radio buttons
Packit 1470ea
        this._cookieRadio = new Gtk.RadioButton ({ label: "Cookie" });
Packit 1470ea
        this._notCookieOne = new Gtk.RadioButton ({ label: "Not cookie",
Packit 1470ea
            group: this._cookieRadio });
Packit 1470ea
        this._notCookieTwo = new Gtk.RadioButton ({ label: "Not cookie",
Packit 1470ea
            group: this._cookieRadio });
Packit 1470ea
Packit 1470ea
        // Arrange the radio buttons in their own grid
Packit 1470ea
        this._radioGrid = new Gtk.Grid ();
Packit 1470ea
        this._radioGrid.attach (this._notCookieOne, 0, 0, 1, 1);
Packit 1470ea
        this._radioGrid.attach (this._cookieRadio, 0, 1, 1, 1);
Packit 1470ea
        this._radioGrid.attach (this._notCookieTwo, 0, 2, 1, 1);
Packit 1470ea
Packit 1470ea
        // Set the button that will be at the top to be active by default
Packit 1470ea
        this._notCookieOne.set_active (true);
Packit 1470ea
Packit 1470ea
        // Create the cookie button
Packit 1470ea
        this._cookieButton = new Gtk.Button ({
Packit 1470ea
            label: "Get a cookie" });
Packit 1470ea
Packit 1470ea
        // Connect the cookie button to the function that handles clicking it
Packit 1470ea
        this._cookieButton.connect ('clicked', this._getACookie.bind(this));
Packit 1470ea
Packit 1470ea
        // Create the label
Packit 1470ea
        this._cookieLabel = new Gtk.Label ({
Packit 1470ea
            label: "Number of cookies: " + cookies });
Packit 1470ea
Packit 1470ea
        // Create a grid to arrange everything inside
Packit 1470ea
        this._grid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER,
Packit 1470ea
            row_spacing: 20 });
Packit 1470ea
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._radioGrid, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 1, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Did you select "cookie" instead of "not cookie"?
Packit 1470ea
        if (this._cookieRadio.get_active()) {
Packit 1470ea
Packit 1470ea
            // Increase the number of cookies by 1 and update the label
Packit 1470ea
            cookies++;
Packit 1470ea
            this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
};
Packit 1470ea
Packit 1470ea
// Run the application
Packit 1470ea
let app = new GettingTheSignal ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
    </section>
Packit 1470ea
Packit 1470ea
    <section id="entrysample">
Packit 1470ea
      <title>Code sample with Entry</title>
Packit 1470ea
      <media type="image" mime="image/png" src="media/03_jssignal_04.png"/>
Packit 1470ea
      #!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
imports.gi.versions.Gtk = '3.0';
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
Packit 1470ea
// We start out with 0 cookies
Packit 1470ea
var cookies = 0;
Packit 1470ea
Packit 1470ea
class GettingTheSignal {
Packit 1470ea
Packit 1470ea
    // Create the application itself
Packit 1470ea
    constructor() {
Packit 1470ea
        this.application = new Gtk.Application();
Packit 1470ea
Packit 1470ea
        // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
        this.application.connect('activate', this._onActivate.bind(this));
Packit 1470ea
        this.application.connect('startup', this._onStartup.bind(this));
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup() {
Packit 1470ea
        this._buildUI();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI() {
Packit 1470ea
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 200,
Packit 1470ea
            default_width: 400,
Packit 1470ea
            border_width: 20,
Packit 1470ea
            title: "Spell 'cookie' to get a cookie!"});
Packit 1470ea
Packit 1470ea
        // Create the text entry field
Packit 1470ea
        this._spellCookie = new Gtk.Entry ();
Packit 1470ea
Packit 1470ea
        // Create the cookie button
Packit 1470ea
        this._cookieButton = new Gtk.Button ({
Packit 1470ea
            label: "Get a cookie" });
Packit 1470ea
Packit 1470ea
        // Connect the cookie button to the function that handles clicking it
Packit 1470ea
        this._cookieButton.connect ('clicked', this._getACookie.bind(this));
Packit 1470ea
Packit 1470ea
        // Create the label
Packit 1470ea
        this._cookieLabel = new Gtk.Label ({
Packit 1470ea
            label: "Number of cookies: " + cookies });
Packit 1470ea
Packit 1470ea
        // Create a grid to arrange everything inside
Packit 1470ea
        this._grid = new Gtk.Grid ({
Packit 1470ea
            halign: Gtk.Align.CENTER,
Packit 1470ea
            valign: Gtk.Align.CENTER,
Packit 1470ea
            row_spacing: 20 });
Packit 1470ea
Packit 1470ea
        // Put everything inside the grid
Packit 1470ea
        this._grid.attach (this._spellCookie, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieButton, 0, 1, 1, 1);
Packit 1470ea
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    _getACookie() {
Packit 1470ea
Packit 1470ea
        // Did you spell "cookie" correctly?
Packit 1470ea
        if ((this._spellCookie.get_text()).toLowerCase() == "cookie") {
Packit 1470ea
Packit 1470ea
            // Increase the number of cookies by 1 and update the label
Packit 1470ea
            cookies++;
Packit 1470ea
            this._cookieLabel.set_label ("Number of cookies: " + cookies);
Packit 1470ea
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
};
Packit 1470ea
Packit 1470ea
// Run the application
Packit 1470ea
let app = new GettingTheSignal ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
    </section>
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
</page>