##// END OF EJS Templates
Added an example that shows how to make a custom date picker widget
Jonathan Frederic -
Show More
This diff has been collapsed as it changes many lines, (1278 lines changed) Show them Hide them
@@ -0,0 +1,1278 b''
1 {
2 "metadata": {
3 "cell_tags": [
4 [
5 "<None>",
6 null
7 ]
8 ],
9 "name": ""
10 },
11 "nbformat": 3,
12 "nbformat_minor": 0,
13 "worksheets": [
14 {
15 "cells": [
16 {
17 "cell_type": "markdown",
18 "metadata": {},
19 "source": [
20 "Before reading, the author recommends the reader to review\n",
21 "\n",
22 "- [MVC prgramming](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)\n",
23 "- [Backbone.js](https://www.codeschool.com/courses/anatomy-of-backbonejs)\n",
24 "- [The widget IPEP](https://github.com/ipython/ipython/wiki/IPEP-23%3A-Backbone.js-Widgets)\n",
25 "- [The original widget PR discussion](https://github.com/ipython/ipython/pull/4374)"
26 ]
27 },
28 {
29 "cell_type": "code",
30 "collapsed": false,
31 "input": [
32 "from IPython.html import widgets # Widget definitions\n",
33 "from IPython.display import display # Used to display widgets in the notebook\n",
34 "\n",
35 "# Enable widgets in this notebook\n",
36 "widgets.init_widget_js()"
37 ],
38 "language": "python",
39 "metadata": {},
40 "outputs": [
41 {
42 "javascript": [
43 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/button.js\");"
44 ],
45 "metadata": {},
46 "output_type": "display_data"
47 },
48 {
49 "javascript": [
50 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/int_range.js\");"
51 ],
52 "metadata": {},
53 "output_type": "display_data"
54 },
55 {
56 "javascript": [
57 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/string.js\");"
58 ],
59 "metadata": {},
60 "output_type": "display_data"
61 },
62 {
63 "javascript": [
64 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/multicontainer.js\");"
65 ],
66 "metadata": {},
67 "output_type": "display_data"
68 },
69 {
70 "javascript": [
71 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/bool.js\");"
72 ],
73 "metadata": {},
74 "output_type": "display_data"
75 },
76 {
77 "javascript": [
78 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/int.js\");"
79 ],
80 "metadata": {},
81 "output_type": "display_data"
82 },
83 {
84 "javascript": [
85 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/selection.js\");"
86 ],
87 "metadata": {},
88 "output_type": "display_data"
89 },
90 {
91 "javascript": [
92 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/float.js\");"
93 ],
94 "metadata": {},
95 "output_type": "display_data"
96 },
97 {
98 "javascript": [
99 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/float_range.js\");"
100 ],
101 "metadata": {},
102 "output_type": "display_data"
103 },
104 {
105 "javascript": [
106 "$.getScript($(\"body\").data(\"baseProjectUrl\") + \"static/notebook/js/widgets/container.js\");"
107 ],
108 "metadata": {},
109 "output_type": "display_data"
110 }
111 ],
112 "prompt_number": 1
113 },
114 {
115 "cell_type": "heading",
116 "level": 1,
117 "metadata": {},
118 "source": [
119 "Abstract"
120 ]
121 },
122 {
123 "cell_type": "markdown",
124 "metadata": {},
125 "source": [
126 "This notebook implements a custom date picker widget. The purpose of this notebook is to demonstrate the widget creation process. To create a custom widget, custom Python and JavaScript is required."
127 ]
128 },
129 {
130 "cell_type": "heading",
131 "level": 1,
132 "metadata": {},
133 "source": [
134 "Section 1 - Basics"
135 ]
136 },
137 {
138 "cell_type": "heading",
139 "level": 2,
140 "metadata": {},
141 "source": [
142 "Python"
143 ]
144 },
145 {
146 "cell_type": "markdown",
147 "metadata": {},
148 "source": [
149 "When starting a project like this, it is often easiest to make an overly simplified base to verify that the underlying framework is working as expected. To start we will create an empty widget and make sure that it can be rendered. The first step is to create the widget in Python."
150 ]
151 },
152 {
153 "cell_type": "code",
154 "collapsed": false,
155 "input": [
156 "# Import the base Widget class and the traitlets Unicode class.\n",
157 "from IPython.html.widgets import Widget\n",
158 "from IPython.utils.traitlets import Unicode\n",
159 "\n",
160 "# Define our DateWidget and its target model and default view.\n",
161 "class DateWidget(Widget):\n",
162 " target_name = Unicode('DateWidgetModel')\n",
163 " default_view_name = Unicode('DatePickerView')"
164 ],
165 "language": "python",
166 "metadata": {},
167 "outputs": [],
168 "prompt_number": 2
169 },
170 {
171 "cell_type": "markdown",
172 "metadata": {},
173 "source": [
174 "- **target_name** is a special `Widget` property that tells the widget framework which Backbone model in the front-end corresponds to this widget.\n",
175 "- **default_view_name** is the default Backbone view to display when the user calls `display` to display an instance of this widget.\n"
176 ]
177 },
178 {
179 "cell_type": "heading",
180 "level": 2,
181 "metadata": {},
182 "source": [
183 "JavaScript"
184 ]
185 },
186 {
187 "cell_type": "markdown",
188 "metadata": {},
189 "source": [
190 "In the IPython notebook [require.js](http://requirejs.org/) is used to load JavaScript dependencies. All IPython widget code depends on `notebook/js/widget.js`. In it the base widget model, base view, and widget manager are defined. We need to use require.js to include this file:"
191 ]
192 },
193 {
194 "cell_type": "code",
195 "collapsed": false,
196 "input": [
197 "%%javascript\n",
198 "\n",
199 "require([\"notebook/js/widget\"], function(){\n",
200 "\n",
201 "});"
202 ],
203 "language": "python",
204 "metadata": {},
205 "outputs": [
206 {
207 "javascript": [
208 "\n",
209 "require([\"notebook/js/widget\"], function(){\n",
210 "\n",
211 "});"
212 ],
213 "metadata": {},
214 "output_type": "display_data",
215 "text": [
216 "<IPython.core.display.Javascript at 0x168b0d0>"
217 ]
218 }
219 ],
220 "prompt_number": 3
221 },
222 {
223 "cell_type": "markdown",
224 "metadata": {},
225 "source": [
226 "The next step is to add a definition for the widget's model. It's important to extend the `IPython.WidgetModel` which extends the Backbone.js base model instead of trying to extend the Backbone.js base model directly. After defining the model, it needs to be registed with the widget manager using the `target_name` used in the Python code."
227 ]
228 },
229 {
230 "cell_type": "code",
231 "collapsed": false,
232 "input": [
233 "%%javascript\n",
234 "\n",
235 "require([\"notebook/js/widget\"], function(){\n",
236 " \n",
237 " // Define the DateModel and register it with the widget manager.\n",
238 " var DateModel = IPython.WidgetModel.extend({});\n",
239 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
240 "});"
241 ],
242 "language": "python",
243 "metadata": {},
244 "outputs": [
245 {
246 "javascript": [
247 "\n",
248 "require([\"notebook/js/widget\"], function(){\n",
249 " \n",
250 " // Define the DateModel and register it with the widget manager.\n",
251 " var DateModel = IPython.WidgetModel.extend({});\n",
252 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
253 "});"
254 ],
255 "metadata": {},
256 "output_type": "display_data",
257 "text": [
258 "<IPython.core.display.Javascript at 0x168df50>"
259 ]
260 }
261 ],
262 "prompt_number": 4
263 },
264 {
265 "cell_type": "markdown",
266 "metadata": {},
267 "source": [
268 "Now that the model is defined, we need to define a view that can be used to represent the model. To do this, the `IPython.WidgetView` is extended. A render function must be defined. The render function is used to render a widget view instance to the DOM. For now the render function renders a div that contains the text *Hello World!* Lastly, the view needs to be registered with the widget manager like the model was.\n",
269 "\n",
270 "**Final JavaScript code below:**"
271 ]
272 },
273 {
274 "cell_type": "code",
275 "collapsed": false,
276 "input": [
277 "%%javascript\n",
278 "\n",
279 "require([\"notebook/js/widget\"], function(){\n",
280 " \n",
281 " // Define the DateModel and register it with the widget manager.\n",
282 " var DateModel = IPython.WidgetModel.extend({});\n",
283 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
284 " \n",
285 " // Define the DatePickerView\n",
286 " var DatePickerView = IPython.WidgetView.extend({\n",
287 " \n",
288 " render: function(){\n",
289 " this.$el = $('<div />')\n",
290 " .html('Hello World!');\n",
291 " },\n",
292 " });\n",
293 " \n",
294 " // Register the DatePickerView with the widget manager.\n",
295 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
296 "});"
297 ],
298 "language": "python",
299 "metadata": {},
300 "outputs": [
301 {
302 "javascript": [
303 "\n",
304 "require([\"notebook/js/widget\"], function(){\n",
305 " \n",
306 " // Define the DateModel and register it with the widget manager.\n",
307 " var DateModel = IPython.WidgetModel.extend({});\n",
308 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
309 " \n",
310 " // Define the DatePickerView\n",
311 " var DatePickerView = IPython.WidgetView.extend({\n",
312 " \n",
313 " render: function(){\n",
314 " this.$el = $('<div />')\n",
315 " .html('Hello World!');\n",
316 " },\n",
317 " });\n",
318 " \n",
319 " // Register the DatePickerView with the widget manager.\n",
320 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
321 "});"
322 ],
323 "metadata": {},
324 "output_type": "display_data",
325 "text": [
326 "<IPython.core.display.Javascript at 0x168f050>"
327 ]
328 }
329 ],
330 "prompt_number": 5
331 },
332 {
333 "cell_type": "heading",
334 "level": 2,
335 "metadata": {},
336 "source": [
337 "Test"
338 ]
339 },
340 {
341 "cell_type": "markdown",
342 "metadata": {},
343 "source": [
344 "To test, create the widget the same way that the other widgets are created."
345 ]
346 },
347 {
348 "cell_type": "code",
349 "collapsed": false,
350 "input": [
351 "my_widget = DateWidget()\n",
352 "display(my_widget)"
353 ],
354 "language": "python",
355 "metadata": {},
356 "outputs": [],
357 "prompt_number": 6
358 },
359 {
360 "cell_type": "heading",
361 "level": 1,
362 "metadata": {},
363 "source": [
364 "Section 2 - Something useful"
365 ]
366 },
367 {
368 "cell_type": "heading",
369 "level": 2,
370 "metadata": {},
371 "source": [
372 "Python"
373 ]
374 },
375 {
376 "cell_type": "markdown",
377 "metadata": {},
378 "source": [
379 "In the last section we created a simple widget that displayed *Hello World!* There was no custom state information associated with the widget. To make an actual date widget, we need to add a property that will be synced between the Python model and the JavaScript model. The new property must be a traitlet property so the widget machinery can automatically handle it. The property needs to be added to the the `_keys` list. The `_keys` list tells the widget machinery what traitlets should be synced with the front-end. Adding this to the code from the last section:"
380 ]
381 },
382 {
383 "cell_type": "code",
384 "collapsed": false,
385 "input": [
386 "# Import the base Widget class and the traitlets Unicode class.\n",
387 "from IPython.html.widgets import Widget\n",
388 "from IPython.utils.traitlets import Unicode\n",
389 "\n",
390 "# Define our DateWidget and its target model and default view.\n",
391 "class DateWidget(Widget):\n",
392 " target_name = Unicode('DateWidgetModel')\n",
393 " default_view_name = Unicode('DatePickerView')\n",
394 " \n",
395 " # Define the custom state properties to sync with the front-end\n",
396 " _keys = ['value']\n",
397 " value = Unicode()"
398 ],
399 "language": "python",
400 "metadata": {},
401 "outputs": [],
402 "prompt_number": 7
403 },
404 {
405 "cell_type": "heading",
406 "level": 2,
407 "metadata": {},
408 "source": [
409 "JavaScript"
410 ]
411 },
412 {
413 "cell_type": "markdown",
414 "metadata": {},
415 "source": [
416 "In the JavaScript there is no need to define the same properties in the JavaScript model. When the JavaScript model is created for the first time, it copies all of the attributes from the Python model. We need to replace *Hello World!* with an actual HTML date picker widget."
417 ]
418 },
419 {
420 "cell_type": "code",
421 "collapsed": false,
422 "input": [
423 "%%javascript\n",
424 "\n",
425 "require([\"notebook/js/widget\"], function(){\n",
426 " \n",
427 " // Define the DateModel and register it with the widget manager.\n",
428 " var DateModel = IPython.WidgetModel.extend({});\n",
429 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
430 " \n",
431 " // Define the DatePickerView\n",
432 " var DatePickerView = IPython.WidgetView.extend({\n",
433 " \n",
434 " render: function(){\n",
435 " \n",
436 " // Create a div to hold our widget.\n",
437 " this.$el = $('<div />');\n",
438 " \n",
439 " // Create the date picker control.\n",
440 " this.$date = $('<input />')\n",
441 " .attr('type', 'date');\n",
442 " },\n",
443 " });\n",
444 " \n",
445 " // Register the DatePickerView with the widget manager.\n",
446 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
447 "});"
448 ],
449 "language": "python",
450 "metadata": {},
451 "outputs": [
452 {
453 "javascript": [
454 "\n",
455 "require([\"notebook/js/widget\"], function(){\n",
456 " \n",
457 " // Define the DateModel and register it with the widget manager.\n",
458 " var DateModel = IPython.WidgetModel.extend({});\n",
459 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
460 " \n",
461 " // Define the DatePickerView\n",
462 " var DatePickerView = IPython.WidgetView.extend({\n",
463 " \n",
464 " render: function(){\n",
465 " \n",
466 " // Create a div to hold our widget.\n",
467 " this.$el = $('<div />');\n",
468 " \n",
469 " // Create the date picker control.\n",
470 " this.$date = $('<input />')\n",
471 " .attr('type', 'date');\n",
472 " },\n",
473 " });\n",
474 " \n",
475 " // Register the DatePickerView with the widget manager.\n",
476 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
477 "});"
478 ],
479 "metadata": {},
480 "output_type": "display_data",
481 "text": [
482 "<IPython.core.display.Javascript at 0x17822d0>"
483 ]
484 }
485 ],
486 "prompt_number": 8
487 },
488 {
489 "cell_type": "markdown",
490 "metadata": {},
491 "source": [
492 "In order to get the HTML date picker to update itself with the value set in the back-end, we need to implement an `update()` method."
493 ]
494 },
495 {
496 "cell_type": "code",
497 "collapsed": false,
498 "input": [
499 "%%javascript\n",
500 "\n",
501 "require([\"notebook/js/widget\"], function(){\n",
502 " \n",
503 " // Define the DateModel and register it with the widget manager.\n",
504 " var DateModel = IPython.WidgetModel.extend({});\n",
505 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
506 " \n",
507 " // Define the DatePickerView\n",
508 " var DatePickerView = IPython.WidgetView.extend({\n",
509 " \n",
510 " render: function(){\n",
511 " \n",
512 " // Create a div to hold our widget.\n",
513 " this.$el = $('<div />');\n",
514 " \n",
515 " // Create the date picker control.\n",
516 " this.$date = $('<input />')\n",
517 " .attr('type', 'date');\n",
518 " },\n",
519 " \n",
520 " update: function() {\n",
521 " \n",
522 " // Set the value of the date control and then call base.\n",
523 " this.$date.val(this.model.get('value')); // ISO format \"YYYY-MM-DDTHH:mm:ss.sssZ\" is required\n",
524 " return IPython.WidgetView.prototype.update.call(this);\n",
525 " },\n",
526 " });\n",
527 " \n",
528 " // Register the DatePickerView with the widget manager.\n",
529 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
530 "});"
531 ],
532 "language": "python",
533 "metadata": {},
534 "outputs": [
535 {
536 "javascript": [
537 "\n",
538 "require([\"notebook/js/widget\"], function(){\n",
539 " \n",
540 " // Define the DateModel and register it with the widget manager.\n",
541 " var DateModel = IPython.WidgetModel.extend({});\n",
542 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
543 " \n",
544 " // Define the DatePickerView\n",
545 " var DatePickerView = IPython.WidgetView.extend({\n",
546 " \n",
547 " render: function(){\n",
548 " \n",
549 " // Create a div to hold our widget.\n",
550 " this.$el = $('<div />');\n",
551 " \n",
552 " // Create the date picker control.\n",
553 " this.$date = $('<input />')\n",
554 " .attr('type', 'date');\n",
555 " },\n",
556 " \n",
557 " update: function() {\n",
558 " \n",
559 " // Set the value of the date control and then call base.\n",
560 " this.$date.val(this.model.get('value')); // ISO format \"YYYY-MM-DDTHH:mm:ss.sssZ\" is required\n",
561 " return IPython.WidgetView.prototype.update.call(this);\n",
562 " },\n",
563 " });\n",
564 " \n",
565 " // Register the DatePickerView with the widget manager.\n",
566 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
567 "});"
568 ],
569 "metadata": {},
570 "output_type": "display_data",
571 "text": [
572 "<IPython.core.display.Javascript at 0x1782390>"
573 ]
574 }
575 ],
576 "prompt_number": 9
577 },
578 {
579 "cell_type": "markdown",
580 "metadata": {},
581 "source": [
582 "To get the changed value from the front-end to publish itself to the back-end, we need to listen to the change event triggered by the HTM date control and set the value in the model. By setting the `this.$el` property of the view, we break the Backbone powered event handling. To fix this, a call to `this.delegateEvents()` must be added after `this.$el` is set. \n",
583 "\n",
584 "After the date change event fires and the new value is set in the model, it's very important that we call `update_other_views(this)` to make the other views on the page update and to let the widget machinery know which view changed the model. This is important because the widget machinery needs to know which cell to route the message callbacks to.\n",
585 "\n",
586 "**Final JavaScript code below:**"
587 ]
588 },
589 {
590 "cell_type": "code",
591 "collapsed": false,
592 "input": [
593 "%%javascript\n",
594 "\n",
595 "require([\"notebook/js/widget\"], function(){\n",
596 " \n",
597 " // Define the DateModel and register it with the widget manager.\n",
598 " var DateModel = IPython.WidgetModel.extend({});\n",
599 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
600 " \n",
601 " // Define the DatePickerView\n",
602 " var DatePickerView = IPython.WidgetView.extend({\n",
603 " \n",
604 " render: function(){\n",
605 " \n",
606 " // Create a div to hold our widget.\n",
607 " this.$el = $('<div />');\n",
608 " this.delegateEvents();\n",
609 " \n",
610 " // Create the date picker control.\n",
611 " this.$date = $('<input />')\n",
612 " .attr('type', 'date')\n",
613 " .appendTo(this.$el);\n",
614 " },\n",
615 " \n",
616 " update: function() {\n",
617 " \n",
618 " // Set the value of the date control and then call base.\n",
619 " this.$date.val(this.model.get('value')); // ISO format \"YYYY-MM-DDTHH:mm:ss.sssZ\" is required\n",
620 " return IPython.WidgetView.prototype.update.call(this);\n",
621 " },\n",
622 " \n",
623 " // Tell Backbone to listen to the change event of input controls (which the HTML date picker is)\n",
624 " events: {\"change\": \"handle_date_change\"},\n",
625 " \n",
626 " // Callback for when the date is changed.\n",
627 " handle_date_change: function(event) {\n",
628 " this.model.set('value', this.$date.val());\n",
629 " this.model.update_other_views(this);\n",
630 " },\n",
631 " \n",
632 " });\n",
633 " \n",
634 " // Register the DatePickerView with the widget manager.\n",
635 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
636 "});"
637 ],
638 "language": "python",
639 "metadata": {},
640 "outputs": [
641 {
642 "javascript": [
643 "\n",
644 "require([\"notebook/js/widget\"], function(){\n",
645 " \n",
646 " // Define the DateModel and register it with the widget manager.\n",
647 " var DateModel = IPython.WidgetModel.extend({});\n",
648 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
649 " \n",
650 " // Define the DatePickerView\n",
651 " var DatePickerView = IPython.WidgetView.extend({\n",
652 " \n",
653 " render: function(){\n",
654 " \n",
655 " // Create a div to hold our widget.\n",
656 " this.$el = $('<div />');\n",
657 " this.delegateEvents();\n",
658 " \n",
659 " // Create the date picker control.\n",
660 " this.$date = $('<input />')\n",
661 " .attr('type', 'date')\n",
662 " .appendTo(this.$el);\n",
663 " },\n",
664 " \n",
665 " update: function() {\n",
666 " \n",
667 " // Set the value of the date control and then call base.\n",
668 " this.$date.val(this.model.get('value')); // ISO format \"YYYY-MM-DDTHH:mm:ss.sssZ\" is required\n",
669 " return IPython.WidgetView.prototype.update.call(this);\n",
670 " },\n",
671 " \n",
672 " // Tell Backbone to listen to the change event of input controls (which the HTML date picker is)\n",
673 " events: {\"change\": \"handle_date_change\"},\n",
674 " \n",
675 " // Callback for when the date is changed.\n",
676 " handle_date_change: function(event) {\n",
677 " this.model.set('value', this.$date.val());\n",
678 " this.model.update_other_views(this);\n",
679 " },\n",
680 " \n",
681 " });\n",
682 " \n",
683 " // Register the DatePickerView with the widget manager.\n",
684 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
685 "});"
686 ],
687 "metadata": {},
688 "output_type": "display_data",
689 "text": [
690 "<IPython.core.display.Javascript at 0x17821d0>"
691 ]
692 }
693 ],
694 "prompt_number": 10
695 },
696 {
697 "cell_type": "heading",
698 "level": 2,
699 "metadata": {},
700 "source": [
701 "Test"
702 ]
703 },
704 {
705 "cell_type": "markdown",
706 "metadata": {},
707 "source": [
708 "To test, create the widget the same way that the other widgets are created."
709 ]
710 },
711 {
712 "cell_type": "code",
713 "collapsed": false,
714 "input": [
715 "my_widget = DateWidget()\n",
716 "display(my_widget)"
717 ],
718 "language": "python",
719 "metadata": {},
720 "outputs": [],
721 "prompt_number": 11
722 },
723 {
724 "cell_type": "markdown",
725 "metadata": {},
726 "source": [
727 "Display the widget again to make sure that both views remain in sync."
728 ]
729 },
730 {
731 "cell_type": "code",
732 "collapsed": false,
733 "input": [
734 "display(my_widget)"
735 ],
736 "language": "python",
737 "metadata": {},
738 "outputs": [],
739 "prompt_number": 12
740 },
741 {
742 "cell_type": "markdown",
743 "metadata": {},
744 "source": [
745 "Read the date from Python"
746 ]
747 },
748 {
749 "cell_type": "code",
750 "collapsed": false,
751 "input": [
752 "my_widget.value"
753 ],
754 "language": "python",
755 "metadata": {},
756 "outputs": [
757 {
758 "metadata": {},
759 "output_type": "pyout",
760 "prompt_number": 13,
761 "text": [
762 "u''"
763 ]
764 }
765 ],
766 "prompt_number": 13
767 },
768 {
769 "cell_type": "markdown",
770 "metadata": {},
771 "source": [
772 "Set the date from Python"
773 ]
774 },
775 {
776 "cell_type": "code",
777 "collapsed": false,
778 "input": [
779 "my_widget.value = \"1999-12-01\" # December 1st, 1999"
780 ],
781 "language": "python",
782 "metadata": {},
783 "outputs": [],
784 "prompt_number": 14
785 },
786 {
787 "cell_type": "heading",
788 "level": 1,
789 "metadata": {},
790 "source": [
791 "Section 3 - Extra credit"
792 ]
793 },
794 {
795 "cell_type": "markdown",
796 "metadata": {},
797 "source": [
798 "In the last section we created a fully working date picker widget. Now we will add custom validation and support for labels. Currently only the ISO date format \"YYYY-MM-DD\" is supported. We will add support for all of the date formats recognized by the 3rd party Python dateutil library."
799 ]
800 },
801 {
802 "cell_type": "heading",
803 "level": 2,
804 "metadata": {},
805 "source": [
806 "Python"
807 ]
808 },
809 {
810 "cell_type": "markdown",
811 "metadata": {},
812 "source": [
813 "The traitlet machinery searches the class that the trait is defined in for methods with \"`_changed`\" suffixed onto their names. Any method with the format \"`X_changed`\" will be called when \"`X`\" is modified. We can take advantage of this to perform validation and parsing of different date string formats. Below a method that listens to value has been added to the DateWidget."
814 ]
815 },
816 {
817 "cell_type": "code",
818 "collapsed": false,
819 "input": [
820 "# Import the base Widget class and the traitlets Unicode class.\n",
821 "from IPython.html.widgets import Widget\n",
822 "from IPython.utils.traitlets import Unicode\n",
823 "\n",
824 "# Define our DateWidget and its target model and default view.\n",
825 "class DateWidget(Widget):\n",
826 " target_name = Unicode('DateWidgetModel')\n",
827 " default_view_name = Unicode('DatePickerView')\n",
828 " \n",
829 " # Define the custom state properties to sync with the front-end\n",
830 " _keys = ['value']\n",
831 " value = Unicode()\n",
832 " \n",
833 " # This function automatically gets called by the traitlet machinery when\n",
834 " # value is modified because of this function's name.\n",
835 " def _value_changed(self, name, old_value, new_value):\n",
836 " pass\n",
837 " "
838 ],
839 "language": "python",
840 "metadata": {},
841 "outputs": [],
842 "prompt_number": 15
843 },
844 {
845 "cell_type": "markdown",
846 "metadata": {},
847 "source": [
848 "Now the function that parses the date string and only sets it in the correct format can be added."
849 ]
850 },
851 {
852 "cell_type": "code",
853 "collapsed": false,
854 "input": [
855 "# Import the dateutil library to parse date strings.\n",
856 "from dateutil import parser\n",
857 "\n",
858 "# Import the base Widget class and the traitlets Unicode class.\n",
859 "from IPython.html.widgets import Widget\n",
860 "from IPython.utils.traitlets import Unicode\n",
861 "\n",
862 "# Define our DateWidget and its target model and default view.\n",
863 "class DateWidget(Widget):\n",
864 " target_name = Unicode('DateWidgetModel')\n",
865 " default_view_name = Unicode('DatePickerView')\n",
866 " \n",
867 " # Define the custom state properties to sync with the front-end\n",
868 " _keys = ['value']\n",
869 " value = Unicode()\n",
870 " \n",
871 " # This function automatically gets called by the traitlet machinery when\n",
872 " # value is modified because of this function's name.\n",
873 " def _value_changed(self, name, old_value, new_value):\n",
874 " \n",
875 " # Parse the date time value.\n",
876 " try:\n",
877 " parsed_date = parser.parse(new_value)\n",
878 " parsed_date_string = parsed_date.strftime(\"%Y-%m-%d\")\n",
879 " except:\n",
880 " parsed_date_string = ''\n",
881 " \n",
882 " # Set the parsed date string if the current date string is different.\n",
883 " if self.value != parsed_date_string:\n",
884 " self.value = parsed_date_string"
885 ],
886 "language": "python",
887 "metadata": {},
888 "outputs": [],
889 "prompt_number": 16
890 },
891 {
892 "cell_type": "markdown",
893 "metadata": {},
894 "source": [
895 "The standard property name used for widget labels is `description`. In the code block below, `description` has been added to the Python widget."
896 ]
897 },
898 {
899 "cell_type": "code",
900 "collapsed": false,
901 "input": [
902 "# Import the dateutil library to parse date strings.\n",
903 "from dateutil import parser\n",
904 "\n",
905 "# Import the base Widget class and the traitlets Unicode class.\n",
906 "from IPython.html.widgets import Widget\n",
907 "from IPython.utils.traitlets import Unicode\n",
908 "\n",
909 "# Define our DateWidget and its target model and default view.\n",
910 "class DateWidget(Widget):\n",
911 " target_name = Unicode('DateWidgetModel')\n",
912 " default_view_name = Unicode('DatePickerView')\n",
913 " \n",
914 " # Define the custom state properties to sync with the front-end\n",
915 " _keys = ['value', 'description']\n",
916 " value = Unicode()\n",
917 " description = Unicode()\n",
918 " \n",
919 " # This function automatically gets called by the traitlet machinery when\n",
920 " # value is modified because of this function's name.\n",
921 " def _value_changed(self, name, old_value, new_value):\n",
922 " \n",
923 " # Parse the date time value.\n",
924 " try:\n",
925 " parsed_date = parser.parse(new_value)\n",
926 " parsed_date_string = parsed_date.strftime(\"%Y-%m-%d\")\n",
927 " except:\n",
928 " parsed_date_string = ''\n",
929 " \n",
930 " # Set the parsed date string if the current date string is different.\n",
931 " if self.value != parsed_date_string:\n",
932 " self.value = parsed_date_string"
933 ],
934 "language": "python",
935 "metadata": {},
936 "outputs": [],
937 "prompt_number": 17
938 },
939 {
940 "cell_type": "markdown",
941 "metadata": {},
942 "source": [
943 "Finally, a callback list is added so the user can perform custom validation. If any one of the callbacks returns False, the new date time is not set.\n",
944 "\n",
945 "**Final Python code below:**"
946 ]
947 },
948 {
949 "cell_type": "code",
950 "collapsed": false,
951 "input": [
952 "# Import the dateutil library to parse date strings.\n",
953 "from dateutil import parser\n",
954 "\n",
955 "# Import the base Widget class and the traitlets Unicode class.\n",
956 "from IPython.html.widgets import Widget\n",
957 "from IPython.utils.traitlets import Unicode\n",
958 "\n",
959 "# Define our DateWidget and its target model and default view.\n",
960 "class DateWidget(Widget):\n",
961 " target_name = Unicode('DateWidgetModel')\n",
962 " default_view_name = Unicode('DatePickerView')\n",
963 " \n",
964 " # Define the custom state properties to sync with the front-end\n",
965 " _keys = ['value', 'description']\n",
966 " value = Unicode()\n",
967 " description = Unicode()\n",
968 " \n",
969 " def __init__(self, **kwargs):\n",
970 " super(DateWidget, self).__init__(**kwargs)\n",
971 " self._validation_callbacks = []\n",
972 " \n",
973 " # This function automatically gets called by the traitlet machinery when\n",
974 " # value is modified because of this function's name.\n",
975 " def _value_changed(self, name, old_value, new_value):\n",
976 " \n",
977 " # Parse the date time value.\n",
978 " try:\n",
979 " parsed_date = parser.parse(new_value)\n",
980 " parsed_date_string = parsed_date.strftime(\"%Y-%m-%d\")\n",
981 " except:\n",
982 " parsed_date = None\n",
983 " parsed_date_string = ''\n",
984 " \n",
985 " # Set the parsed date string if the current date string is different.\n",
986 " if old_value != new_value:\n",
987 " if self.handle_validate(parsed_date):\n",
988 " self.value = parsed_date_string\n",
989 " else:\n",
990 " self.value = old_value\n",
991 " self.send_state() # The traitlet event won't fire since the value isn't changing.\n",
992 " # We need to force the back-end to send the front-end the state\n",
993 " # to make sure that the date control date doesn't change.\n",
994 " \n",
995 " \n",
996 " # Allow the user to register custom validation callbacks.\n",
997 " # callback(new value as a datetime object)\n",
998 " def on_validate(self, callback, remove=False):\n",
999 " if remove and callback in self._validation_callbacks:\n",
1000 " self._validation_callbacks.remove(callback)\n",
1001 " elif (not remove) and (not callback in self._validation_callbacks):\n",
1002 " self._validation_callbacks.append(callback)\n",
1003 " \n",
1004 " # Call user validation callbacks. Return True if valid.\n",
1005 " def handle_validate(self, new_value):\n",
1006 " for callback in self._validation_callbacks:\n",
1007 " if not callback(new_value):\n",
1008 " return False\n",
1009 " return True\n",
1010 " "
1011 ],
1012 "language": "python",
1013 "metadata": {},
1014 "outputs": [],
1015 "prompt_number": 18
1016 },
1017 {
1018 "cell_type": "heading",
1019 "level": 2,
1020 "metadata": {},
1021 "source": [
1022 "JavaScript"
1023 ]
1024 },
1025 {
1026 "cell_type": "markdown",
1027 "metadata": {},
1028 "source": [
1029 "Using the Javascript code from the last section, we add a label to the date time object. The label is a div with the `widget-hlabel` class applied to it. The `widget-hlabel` is a class provided by the widget framework that applies special styling to a div to make it look like the rest of the horizontal labels used with the built in widgets. Similar to the `widget-hlabel` class is the `widget-hbox-single` class. The `widget-hbox-single` class applies special styling to widget containers that store a single line horizontal widget. \n",
1030 "\n",
1031 "We hide the label if the description value is blank."
1032 ]
1033 },
1034 {
1035 "cell_type": "code",
1036 "collapsed": false,
1037 "input": [
1038 "%%javascript\n",
1039 "\n",
1040 "require([\"notebook/js/widget\"], function(){\n",
1041 " \n",
1042 " // Define the DateModel and register it with the widget manager.\n",
1043 " var DateModel = IPython.WidgetModel.extend({});\n",
1044 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
1045 " \n",
1046 " // Define the DatePickerView\n",
1047 " var DatePickerView = IPython.WidgetView.extend({\n",
1048 " \n",
1049 " render: function(){\n",
1050 " \n",
1051 " // Create a div to hold our widget.\n",
1052 " this.$el = $('<div />')\n",
1053 " .addClass('widget-hbox-single'); // Apply this class to the widget container to make\n",
1054 " // it fit with the other built in widgets.\n",
1055 " this.delegateEvents();\n",
1056 " \n",
1057 " // Create a label.\n",
1058 " this.$label = $('<div />')\n",
1059 " .addClass('widget-hlabel')\n",
1060 " .appendTo(this.$el)\n",
1061 " .hide(); // Hide the label by default.\n",
1062 " \n",
1063 " // Create the date picker control.\n",
1064 " this.$date = $('<input />')\n",
1065 " .attr('type', 'date')\n",
1066 " .appendTo(this.$el);\n",
1067 " },\n",
1068 " \n",
1069 " update: function() {\n",
1070 " \n",
1071 " // Set the value of the date control and then call base.\n",
1072 " this.$date.val(this.model.get('value')); // ISO format \"YYYY-MM-DDTHH:mm:ss.sssZ\" is required\n",
1073 " \n",
1074 " // Hide or show the label depending on the existance of a description.\n",
1075 " var description = this.model.get('description');\n",
1076 " if (description == undefined || description == '') {\n",
1077 " this.$label.hide();\n",
1078 " } else {\n",
1079 " this.$label.show();\n",
1080 " this.$label.html(description);\n",
1081 " }\n",
1082 " \n",
1083 " return IPython.WidgetView.prototype.update.call(this);\n",
1084 " },\n",
1085 " \n",
1086 " // Tell Backbone to listen to the change event of input controls (which the HTML date picker is)\n",
1087 " events: {\"change\": \"handle_date_change\"},\n",
1088 " \n",
1089 " // Callback for when the date is changed.\n",
1090 " handle_date_change: function(event) {\n",
1091 " this.model.set('value', this.$date.val());\n",
1092 " this.model.update_other_views(this);\n",
1093 " },\n",
1094 " \n",
1095 " });\n",
1096 " \n",
1097 " // Register the DatePickerView with the widget manager.\n",
1098 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
1099 "});"
1100 ],
1101 "language": "python",
1102 "metadata": {},
1103 "outputs": [
1104 {
1105 "javascript": [
1106 "\n",
1107 "require([\"notebook/js/widget\"], function(){\n",
1108 " \n",
1109 " // Define the DateModel and register it with the widget manager.\n",
1110 " var DateModel = IPython.WidgetModel.extend({});\n",
1111 " IPython.notebook.widget_manager.register_widget_model('DateWidgetModel', DateModel);\n",
1112 " \n",
1113 " // Define the DatePickerView\n",
1114 " var DatePickerView = IPython.WidgetView.extend({\n",
1115 " \n",
1116 " render: function(){\n",
1117 " \n",
1118 " // Create a div to hold our widget.\n",
1119 " this.$el = $('<div />')\n",
1120 " .addClass('widget-hbox-single'); // Apply this class to the widget container to make\n",
1121 " // it fit with the other built in widgets.\n",
1122 " this.delegateEvents();\n",
1123 " \n",
1124 " // Create a label.\n",
1125 " this.$label = $('<div />')\n",
1126 " .addClass('widget-hlabel')\n",
1127 " .appendTo(this.$el)\n",
1128 " .hide(); // Hide the label by default.\n",
1129 " \n",
1130 " // Create the date picker control.\n",
1131 " this.$date = $('<input />')\n",
1132 " .attr('type', 'date')\n",
1133 " .appendTo(this.$el);\n",
1134 " },\n",
1135 " \n",
1136 " update: function() {\n",
1137 " \n",
1138 " // Set the value of the date control and then call base.\n",
1139 " this.$date.val(this.model.get('value')); // ISO format \"YYYY-MM-DDTHH:mm:ss.sssZ\" is required\n",
1140 " \n",
1141 " // Hide or show the label depending on the existance of a description.\n",
1142 " var description = this.model.get('description');\n",
1143 " if (description == undefined || description == '') {\n",
1144 " this.$label.hide();\n",
1145 " } else {\n",
1146 " this.$label.show();\n",
1147 " this.$label.html(description);\n",
1148 " }\n",
1149 " \n",
1150 " return IPython.WidgetView.prototype.update.call(this);\n",
1151 " },\n",
1152 " \n",
1153 " // Tell Backbone to listen to the change event of input controls (which the HTML date picker is)\n",
1154 " events: {\"change\": \"handle_date_change\"},\n",
1155 " \n",
1156 " // Callback for when the date is changed.\n",
1157 " handle_date_change: function(event) {\n",
1158 " this.model.set('value', this.$date.val());\n",
1159 " this.model.update_other_views(this);\n",
1160 " },\n",
1161 " \n",
1162 " });\n",
1163 " \n",
1164 " // Register the DatePickerView with the widget manager.\n",
1165 " IPython.notebook.widget_manager.register_widget_view('DatePickerView', DatePickerView);\n",
1166 "});"
1167 ],
1168 "metadata": {},
1169 "output_type": "display_data",
1170 "text": [
1171 "<IPython.core.display.Javascript at 0x179f790>"
1172 ]
1173 }
1174 ],
1175 "prompt_number": 19
1176 },
1177 {
1178 "cell_type": "heading",
1179 "level": 2,
1180 "metadata": {},
1181 "source": [
1182 "Test"
1183 ]
1184 },
1185 {
1186 "cell_type": "markdown",
1187 "metadata": {},
1188 "source": [
1189 "To test the drawing of the label we create the widget like normal but supply the additional description property a value."
1190 ]
1191 },
1192 {
1193 "cell_type": "code",
1194 "collapsed": false,
1195 "input": [
1196 "# Add some additional widgets for aesthetic purpose\n",
1197 "display(widgets.StringWidget(description=\"First:\"))\n",
1198 "display(widgets.StringWidget(description=\"Last:\"))\n",
1199 "\n",
1200 "my_widget = DateWidget(description=\"DOB:\")\n",
1201 "display(my_widget)"
1202 ],
1203 "language": "python",
1204 "metadata": {},
1205 "outputs": [],
1206 "prompt_number": 20
1207 },
1208 {
1209 "cell_type": "markdown",
1210 "metadata": {},
1211 "source": [
1212 "Since the date widget uses `value` and `description`, we can also display its value using a `TextBoxView`. The allows us to look at the raw date value being passed to and from the back-end and front-end."
1213 ]
1214 },
1215 {
1216 "cell_type": "code",
1217 "collapsed": false,
1218 "input": [
1219 "\n",
1220 "display(my_widget, view_name=\"TextBoxView\")"
1221 ],
1222 "language": "python",
1223 "metadata": {},
1224 "outputs": [],
1225 "prompt_number": 21
1226 },
1227 {
1228 "cell_type": "markdown",
1229 "metadata": {},
1230 "source": [
1231 "Now we will try to create a widget that only accepts dates in the year 2013. We render the widget without a description to verify that it can still render without a label."
1232 ]
1233 },
1234 {
1235 "cell_type": "code",
1236 "collapsed": false,
1237 "input": [
1238 "my_widget = DateWidget()\n",
1239 "display(my_widget)\n",
1240 "\n",
1241 "def validate_date(date):\n",
1242 " return not date is None and date.year == 2013\n",
1243 "my_widget.on_validate(validate_date)"
1244 ],
1245 "language": "python",
1246 "metadata": {},
1247 "outputs": [],
1248 "prompt_number": 22
1249 },
1250 {
1251 "cell_type": "code",
1252 "collapsed": false,
1253 "input": [
1254 "# Try setting a valid date\n",
1255 "my_widget.value = \"December 2, 2013\""
1256 ],
1257 "language": "python",
1258 "metadata": {},
1259 "outputs": [],
1260 "prompt_number": 23
1261 },
1262 {
1263 "cell_type": "code",
1264 "collapsed": false,
1265 "input": [
1266 "# Try setting an invalid date\n",
1267 "my_widget.value = \"June 12, 1999\""
1268 ],
1269 "language": "python",
1270 "metadata": {},
1271 "outputs": [],
1272 "prompt_number": 24
1273 }
1274 ],
1275 "metadata": {}
1276 }
1277 ]
1278 } No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now