-
Notifications
You must be signed in to change notification settings - Fork 2
/
demo-updated.js
67 lines (56 loc) · 2.1 KB
/
demo-updated.js
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
// this code is loosely coupled across widgets using messaging
// edit widget
$( document ).ready( function() {
var counter = 0;
// blank the input fields, disable the buttons and update list
function reset() {
$( "#name" ).val( "" ).focus();
$( "#key" ).val( "" );
$( "#save" ).prop( "disabled", true );
$( "#cancel" ).prop( "disabled", true );
$.hub.publish( "cancel", {} );
}
// buttons are only disabled when input box is blank
$( "#name" ).change( function() {
$( "#save" ).prop( "disabled", !$( this ).val() );
$( "#cancel" ).prop( "disabled", !$( this ).val() );
} );
// don't wait for blur to trigger change
$( "#name" ).keyup( function() {
$( this ).change();
} );
// either update or create a new entry in the list, then reset the form
$( "#save" ).click( function() {
var key = $( "#key" ).val() || ( "key" + counter++ );
$.hub.publish( "save", { "key": key, "name": $( "#name" ).val() } );
reset();
} );
// reset the form
$( "#cancel" ).click( function() {
reset();
} );
$.hub.subscribe( "edit", function( channel, message ) {
$( "#name" ).val( message.name ).change().focus();
$( "#key" ).val( message.key );
});
} );
// list widget
$( document ).ready( function() {
// when a list item clicked, mark active and prefill edit form
$( "#list ul li" ).live( "click", function() {
$( "#list ul li" ).removeClass( "active" );
$( this ).addClass( "active" );
$.hub.publish( "edit", { "key": $( this ).attr( "id" ), "name": $( this ).text() } );
} );
$.hub.subscribe( "save", function( channel, message ) {
var $key = $( "#" + message.key );
if ( $key.length) {
$key.text( message.name );
} else {
$( "#list ul" ).append( "<li id='" + message.key + "'>" + message.name + "</li>" );
}
});
$.hub.subscribe( "cancel", function( channel, message ) {
$( "#list ul li" ).removeClass( "active" );
});
} );