File: 03_getting_the_signal.js.page

package info (click to toggle)
gnome-devel-docs 3.14.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 46,300 kB
  • ctags: 630
  • sloc: xml: 2,321; ansic: 2,040; python: 1,807; makefile: 747; sh: 504; cpp: 131
file content (779 lines) | stat: -rw-r--r-- 32,069 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
<?xml version="1.0" encoding="utf-8"?>
<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">
  <info>
    <link type="guide" xref="beginner.js#tutorials"/>
    <link type="seealso" xref="button.js"/>
    <link type="seealso" xref="entry.js"/>
    <link type="seealso" xref="radiobutton.js"/>
    <link type="seealso" xref="switch.js"/>
    <revision version="0.1" date="2012-08-12" status="draft"/>

    <credit type="author copyright">
      <name>Taryn Fox</name>
      <email its:translate="no">jewelfox@fursona.net</email>
      <years>2012</years>
    </credit>

    <desc>Crie Buttons e outros widgets que fazem coisas quando clicados.</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Rafael Ferreira</mal:name>
      <mal:email>rafael.f.f1@gmail.com</mal:email>
      <mal:years>2013</mal:years>
    </mal:credit>
  </info>

  <title>3. Obtendo o Signal</title>
  <synopsis>
    <p>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.</p>
  </synopsis>

  <links type="section"/>

  <section id="application">
    <title>Um aplicativo básico</title>
    <p>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.</p>
    <p>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.</p>
    <p>Aqui está um exemplo extremamente básico:</p>

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

    <p>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.</p>
    <note style="tip"><p>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.</p></note>
    <p>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.</p>
    <code mime="application/javascript">
#!/usr/bin/gjs

const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

// Nós começamos com 0 cookies
var cookies = 0;

const GettingTheSignal = new Lang.Class({
    Name: 'Obtendo o Signal',

    // Cria o aplicativo em si
    _init: function() {
        this.application = new Gtk.Application();

        // Conecta os sinais 'activate' e 'startup' às funções de chamada
        this.application.connect('activate', Lang.bind(this, this._onActivate));
        this.application.connect('startup', Lang.bind(this, this._onStartup));
    },

    // Função de chamada para o sinal 'activate' apresenta uma janela quando ativa
    _onActivate: function() {
        this._window.present();
    },

    // Função de chamada para o sinal 'startup' constrói a interface gráfica
    _onStartup: function() {
        this._buildUI ();
    },
</code>
    <p>Dê uma olhada na parte que usa o método de conexão do nosso aplicativo e Lang.bind, para conectar seus sinais de ativação e inicialização à função que apresenta a janela e constrói a interface gráfica. Nós vamos fazer a mesma coisa com o nosso Button quando nós chegarmos nele, porém nós vamos conectar o seu sinal de "clicado".</p>
  </section>

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

    <p>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.</p>
    <code mime="application/javascript">
    // Compila a interface gráfica do aplicativo
    _buildUI: function() {
</code>

    <p>Primeiro, nós criamos a janela em si:</p>
    <code mime="application/javascript">
        // Cria a janela do aplicativo
        this._window = new Gtk.ApplicationWindow({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            default_height: 200,
            default_width: 400,
            title: "Clique no botão para obter um cookie!"});
</code>
    <p>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.</p>
    <p>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.</p>
    <code mime="application/javascript">
        // Cria o rótulo
        this._cookieLabel = new Gtk.Label ({
            label: "Número de cookies: " + cookies });
</code>

    <p>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.</p>
    <code mime="application/javascript">
        // Cria o botão do cookie
        this._cookieButton = new Gtk.Button ({ label: "Obter um cookie" });

        // Conecta o botão do cookie à função que lida o clique nele
        this._cookieButton.connect ('clicked', Lang.bind (this, this._getACookie));
</code>
    <p>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.</p>
    <code mime="application/javascript">
        // Cria uma grade para organizar tudo dentro
        this._grid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            row_spacing: 20 });

        // Coloca tudo dentro da grade
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
        this._grid.attach (this._cookieLabel, 0, 1, 1, 1);

        // Adiciona a grade à janela
        this._window.add (this._grid);

        // Mostra a janela e todos os widgets filhos
        this._window.show_all();

    },
</code>
    <p>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.</p>
    <note style="tip"><p>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.</p></note>
    <code mime="application/javascript">
    _getACookie: function() {

        // Aumenta o número de cookies em 1 e atualiza o rótulo
        cookies++;
        this._cookieLabel.set_label ("Número de cookies: " + cookies);

    }

});
</code>

    <p>Finalmente, nós executamos o aplicativo, usando o mesmo tipo de código de nosso último tutorial.</p>
    <code mime="application/javascript">
// Executa o aplicativo
let app = new GettingTheSignal ();
app.application.run (ARGV);
</code>
  </section>

  <section id="switch">
    <title>Flip the switch</title>
    <p>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.</p>

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

    <p>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.</p>

    <p>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.</p>
    <note style="tip"><p>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.</p></note>
    <p>Here's how we create the Switch:</p>
    <code mime="application/javascript"><![CDATA[
        // Create the switch that controls whether or not you can win
        this._cookieSwitch = new Gtk.Switch ();
]]></code>

    <p>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:</p>
    <code mime="application/javascript"><![CDATA[
        // Connect the switch to the function that handles it
        this._cookieSwitch.connect ('notify::active', Lang.bind (this, this._cookieDispenser));
]]></code>

    <p>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.</p>
    <code mime="application/javascript"><![CDATA[
        this._cookieSwitch = new Gtk.Switch ({ active: true });
]]></code>

    <p>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:</p>
    <code mime="application/javascript"><![CDATA[
        // Create the switch that controls whether or not you can win
        this._cookieSwitch = new Gtk.Switch ();

        // Create the label to go with the switch
        this._switchLabel = new Gtk.Label ({
            label: "Cookie dispenser" });

        // Create a grid for the switch and its label
        this._switchGrid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER });

        // Put the switch and its label inside that grid
        this._switchGrid.attach (this._switchLabel, 0, 0, 1, 1);
        this._switchGrid.attach (this._cookieSwitch, 1, 0, 1, 1);
]]></code>

    <p>And now we arrange everything in the larger Grid like so.</p>
    <code mime="application/javascript"><![CDATA[
        // Put everything inside the grid
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
        this._grid.attach (this._switchGrid, 0, 1, 1, 1);
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
]]></code>

    <p>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.</p>
    <note style="tip"><p>When a method is used in an if statement like this, the code inside the if statement is executed if the method returns true.</p></note>
    <code mime="application/javascript"><![CDATA[
    _getACookie: function() {

        // Is the cookie dispenser turned on?
        if (this._cookieSwitch.get_active()) {

            // Increase the number of cookies by 1 and update the label
            cookies++;
            this._cookieLabel.set_label ("Number of cookies: " + cookies);

        }

    }
]]></code>

  </section>

  <section id="radio">
    <title>Tuning the radio</title>

    <p>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.</p>

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

    <p>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.</p>
    <code mime="application/javascript"><![CDATA[
        // Create the application window
        this._window = new Gtk.ApplicationWindow({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            default_height: 200,
            default_width: 400,
            border_width: 20,
            title: "Choose the one that says 'cookie'!"});
]]></code>

    <p>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.</p>
    <code mime="application/javascript"><![CDATA[
        // Create the radio buttons
        this._cookieRadio = new Gtk.RadioButton ({ label: "Cookie" });
        this._notCookieOne = new Gtk.RadioButton ({ label: "Not cookie",
            group: this._cookieRadio });
        this._notCookieTwo = new Gtk.RadioButton ({ label: "Not cookie",
            group: this._cookieRadio });
]]></code>

    <p>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.</p>
    <code mime="application/javascript"><![CDATA[
        // Arrange the radio buttons in their own grid
        this._radioGrid = new Gtk.Grid ();
        this._radioGrid.attach (this._notCookieOne, 0, 0, 1, 1);
        this._radioGrid.attach (this._cookieRadio, 0, 1, 1, 1);
        this._radioGrid.attach (this._notCookieTwo, 0, 2, 1, 1);
]]></code>

    <p>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.</p>
    <note style="tip"><p>We could also set its active property to true when we create it.</p></note>
    <code mime="application/javascript"><![CDATA[
        // Set the button that will be at the top to be active by default
        this._notCookieOne.set_active (true);
]]></code>

    <p>Now we arrange everything in our main Grid like usual ...</p>
    <code mime="application/javascript"><![CDATA[
        // Put everything inside the grid
        this._grid.attach (this._radioGrid, 0, 0, 1, 1);
        this._grid.attach (this._cookieButton, 0, 1, 1, 1);
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
]]></code>

    <p>And then we change our _getACookie function to test to see if the cookie button is the one that's selected.</p>
    <code mime="application/javascript"><![CDATA[
    _getACookie: function() {

        // Did you select "cookie" instead of "not cookie"?
        if (this._cookieRadio.get_active()) {

            // Increase the number of cookies by 1 and update the label
            cookies++;
            this._cookieLabel.set_label ("Number of cookies: " + cookies);

        }

    }
]]></code>

  </section>

  <section id="spell">
    <title>Can you spell "cookie"?</title>

    <p>The last input widget we're going to cover is the Entry widget, which is used for single-line text entry.</p>
    <note style="tip"><p>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.</p></note>
    <media type="image" mime="image/png" src="media/03_jssignal_04.png"/>

    <p>After we change the window's name, we create the Entry widget.</p>
    <code mime="application/javascript"><![CDATA[
        // Create the text entry field
        this._spellCookie = new Gtk.Entry ();
]]></code>

    <p>Next, we arrange everything in the Grid ... </p>
    <code mime="application/javascript"><![CDATA[
        // Put everything inside the grid
        this._grid.attach (this._spellCookie, 0, 0, 1, 1);
        this._grid.attach (this._cookieButton, 0, 1, 1, 1);
        this._grid.attach (this._cookieLabel, 0, 2, 1, 1);
]]></code>

    <p>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.</p>
    <note style="tip"><p>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.</p></note>
    <code mime="application/javascript"><![CDATA[
    _getACookie: function() {

        // Did you spell "cookie" correctly?
        if ((this._spellCookie.get_text()).toLowerCase() == "cookie") {

            // Increase the number of cookies by 1 and update the label
            cookies++;
            this._cookieLabel.set_label ("Number of cookies: " + cookies);

        }

    }
]]></code>

  </section>

  <section id="whats_next">
    <title>O que vem em seguida?</title>
    <p>Keep reading, if you'd like to see the complete code for each version of our cookie maker application.</p>
    <note style="tip"><p>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.</p></note>

  </section>

  <section id="complete">
    <title>Complete code samples</title>

    <links type="section"/>

    <section id="buttonsample">
      <title>Code sample with Button</title>
      <media type="image" mime="image/png" src="media/03_jssignal_01.png"/>
      <code mime="application/javascript" style="numbered">#!/usr/bin/gjs

const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

// We start out with 0 cookies
var cookies = 0;

const GettingTheSignal = new Lang.Class({
    Name: 'Getting the Signal',

    // Create the application itself
    _init: function() {
        this.application = new Gtk.Application();

        // Connect 'activate' and 'startup' signals to the callback functions
        this.application.connect('activate', Lang.bind(this, this._onActivate));
        this.application.connect('startup', Lang.bind(this, this._onStartup));
    },

    // Callback function for 'activate' signal presents window when active
    _onActivate: function() {
        this._window.present();
    },

    // Callback function for 'startup' signal builds the UI
    _onStartup: function() {
        this._buildUI ();
    },



    // Build the application's UI
    _buildUI: function() {

        // Create the application window
        this._window = new Gtk.ApplicationWindow({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            default_height: 200,
            default_width: 400,
            title: "Click the button to get a cookie!"});

        // Create the label
        this._cookieLabel = new Gtk.Label ({
            label: "Number of cookies: " + cookies });

        // Create the cookie button
        this._cookieButton = new Gtk.Button ({ label: "Get a cookie" });

        // Connect the cookie button to the function that handles clicking it
        this._cookieButton.connect ('clicked', Lang.bind (this, this._getACookie));

        // Create a grid to arrange everything inside
        this._grid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            row_spacing: 20 });

        // Put everything inside the grid
        this._grid.attach (this._cookieButton, 0, 0, 1, 1);
        this._grid.attach (this._cookieLabel, 0, 1, 1, 1);

        // Add the grid to the window
        this._window.add (this._grid);

        // Show the window and all child widgets
        this._window.show_all();

    },



    _getACookie: function() {

        // Increase the number of cookies by 1 and update the label
        cookies++;
        this._cookieLabel.set_label ("Number of cookies: " + cookies);

    }

});

// Run the application
let app = new GettingTheSignal ();
app.application.run (ARGV);
</code>
    </section>

    <section id="switchsample">
      <title>Code sample with Switch</title>
      <media type="image" mime="image/png" src="media/03_jssignal_02.png"/>
      <code mime="application/javascript" style="numbered">#!/usr/bin/gjs

const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

// We start out with 0 cookies
var cookies = 0;

const GettingTheSignal = new Lang.Class({
    Name: 'Getting the Signal',

    // Create the application itself
    _init: function() {
        this.application = new Gtk.Application();

        // Connect 'activate' and 'startup' signals to the callback functions
        this.application.connect('activate', Lang.bind(this, this._onActivate));
        this.application.connect('startup', Lang.bind(this, this._onStartup));
    },

    // Callback function for 'activate' signal presents window when active
    _onActivate: function() {
        this._window.present();
    },

    // Callback function for 'startup' signal builds the UI
    _onStartup: function() {
        this._buildUI ();
    },



    // Build the application's UI
    _buildUI: function() {

        // Create the application window
        this._window = new Gtk.ApplicationWindow({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            default_height: 200,
            default_width: 400,
            title: "Click the button to get a cookie!"});

        // Create the label
        this._cookieLabel = new Gtk.Label ({
            label: "Number of cookies: " + cookies });

        // Create the cookie button
        this._cookieButton = new Gtk.Button ({
            label: "Get a cookie" });

        // Connect the cookie button to the function that handles clicking it
        this._cookieButton.connect ('clicked', Lang.bind (this, this._getACookie));

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

        // Create the label to go with the switch
        this._switchLabel = new Gtk.Label ({
            label: "Cookie dispenser" });

        // Create a grid for the switch and its label
        this._switchGrid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER });

        // Put the switch and its label inside that grid
        this._switchGrid.attach (this._switchLabel, 0, 0, 1, 1);
        this._switchGrid.attach (this._cookieSwitch, 1, 0, 1, 1);

        // Create a grid to arrange everything else inside
        this._grid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            row_spacing: 20 });

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

        // Add the grid to the window
        this._window.add (this._grid);

        // Show the window and all child widgets
        this._window.show_all();

    },



    _getACookie: function() {

        // Is the cookie dispenser turned on?
        if (this._cookieSwitch.get_active()) {

            // Increase the number of cookies by 1 and update the label
            cookies++;
            this._cookieLabel.set_label ("Number of cookies: " + cookies);

        }

    }

});

// Run the application
let app = new GettingTheSignal ();
app.application.run (ARGV);
</code>
    </section>

    <section id="radiobuttonsample">
      <title>Code sample with RadioButton</title>
      <media type="image" mime="image/png" src="media/03_jssignal_03.png"/>
      <code mime="application/javascript" style="numbered">#!/usr/bin/gjs

const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

// We start out with 0 cookies
var cookies = 0;

const GettingTheSignal = new Lang.Class({
    Name: 'Getting the Signal',

    // Create the application itself
    _init: function() {
        this.application = new Gtk.Application();

        // Connect 'activate' and 'startup' signals to the callback functions
        this.application.connect('activate', Lang.bind(this, this._onActivate));
        this.application.connect('startup', Lang.bind(this, this._onStartup));
    },

    // Callback function for 'activate' signal presents window when active
    _onActivate: function() {
        this._window.present();
    },

    // Callback function for 'startup' signal builds the UI
    _onStartup: function() {
        this._buildUI ();
    },



    // Build the application's UI
    _buildUI: function() {

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

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

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

        // Set the button that will be at the top to be active by default
        this._notCookieOne.set_active (true);

        // Create the cookie button
        this._cookieButton = new Gtk.Button ({
            label: "Get a cookie" });

        // Connect the cookie button to the function that handles clicking it
        this._cookieButton.connect ('clicked', Lang.bind (this, this._getACookie));

        // Create the label
        this._cookieLabel = new Gtk.Label ({
            label: "Number of cookies: " + cookies });

        // Create a grid to arrange everything inside
        this._grid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            row_spacing: 20 });

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

        // Add the grid to the window
        this._window.add (this._grid);

        // Show the window and all child widgets
        this._window.show_all();

    },



    _getACookie: function() {

        // Did you select "cookie" instead of "not cookie"?
        if (this._cookieRadio.get_active()) {

            // Increase the number of cookies by 1 and update the label
            cookies++;
            this._cookieLabel.set_label ("Number of cookies: " + cookies);

        }

    }

});

// Run the application
let app = new GettingTheSignal ();
app.application.run (ARGV);
</code>
    </section>

    <section id="entrysample">
      <title>Code sample with Entry</title>
      <media type="image" mime="image/png" src="media/03_jssignal_04.png"/>
      <code mime="application/javascript" style="numbered">#!/usr/bin/gjs

const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

// We start out with 0 cookies
var cookies = 0;

const GettingTheSignal = new Lang.Class({
    Name: 'Getting the Signal',

    // Create the application itself
    _init: function() {
        this.application = new Gtk.Application();

        // Connect 'activate' and 'startup' signals to the callback functions
        this.application.connect('activate', Lang.bind(this, this._onActivate));
        this.application.connect('startup', Lang.bind(this, this._onStartup));
    },

    // Callback function for 'activate' signal presents window when active
    _onActivate: function() {
        this._window.present();
    },

    // Callback function for 'startup' signal builds the UI
    _onStartup: function() {
        this._buildUI ();
    },



    // Build the application's UI
    _buildUI: function() {

        // Create the application window
        this._window = new Gtk.ApplicationWindow({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            default_height: 200,
            default_width: 400,
            border_width: 20,
            title: "Spell 'cookie' to get a cookie!"});

        // Create the text entry field
        this._spellCookie = new Gtk.Entry ();

        // Create the cookie button
        this._cookieButton = new Gtk.Button ({
            label: "Get a cookie" });

        // Connect the cookie button to the function that handles clicking it
        this._cookieButton.connect ('clicked', Lang.bind (this, this._getACookie));

        // Create the label
        this._cookieLabel = new Gtk.Label ({
            label: "Number of cookies: " + cookies });

        // Create a grid to arrange everything inside
        this._grid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            row_spacing: 20 });

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

        // Add the grid to the window
        this._window.add (this._grid);

        // Show the window and all child widgets
        this._window.show_all();

    },



    _getACookie: function() {

        // Did you spell "cookie" correctly?
        if ((this._spellCookie.get_text()).toLowerCase() == "cookie") {

            // Increase the number of cookies by 1 and update the label
            cookies++;
            this._cookieLabel.set_label ("Number of cookies: " + cookies);

        }

    }

});

// Run the application
let app = new GettingTheSignal ();
app.application.run (ARGV);
</code>
    </section>

  </section>

</page>