Skip to content
This repository
tree: fb970bd7cd
Fetching contributors…

Cannot retrieve contributors at this time

file 6351 lines (5587 sloc) 616.702 kb
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 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Developing Backbone.js Applications - </title>
  <style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
  margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > span.bn { color: #40a070; }
code > span.fl { color: #40a070; }
code > span.ch { color: #4070a0; }
code > span.st { color: #4070a0; }
code > span.co { color: #60a0b0; font-style: italic; }
code > span.ot { color: #007020; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #06287e; }
code > span.er { color: #ff0000; font-weight: bold; }
  </style>
  <link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<p>
<h1>Developing Backbone.js Applications</h1>
<h3>By Addy Osmani <a href="http://twitter.com/addyosmani">@addyosmani</a></h3>
</p>
<div style="width:500px">

<iframe src="http://ghbtns.com/github-btn.html?user=addyosmani&repo=backbone-fundamentals&type=watch&count=true"
  allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>

 <iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.1333103182.html#_=1333404284780&amp;count=horizontal&amp;id=twitter-widget-0&amp;lang=en&amp;original_referer=http%3A%2F%2Faddyosmani.github.com%2Fbackbone-fundamentals%2F&amp;size=m&amp;text=Developing%20Backbone.js%20Applications&amp;url=https%3A%2F%2Fgithub.com%2Faddyosmani%2Fbackbone-fundamentals&amp;via=addy_osmani" class="twitter-share-button twitter-count-horizontal" style="width: 107px; height: 20px; " title="Twitter Tweet Button"></iframe>
<script id="twitter-wjs" src="//platform.twitter.com/widgets.js"></script><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

  <p>&nbsp;<br></p>
</div>
<h2 id="prelude">Prelude</h2>
<p><img src="img/logo.jpg" style="float:left"/> Welcome to my (in-progress) book about the <a href="http://documentcloud.github.com/backbone/">Backbone.js</a> framework for structuring JavaScript applications. It's released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">license</a> meaning you can both grab a copy of the book for free or help to further <a href="https://github.com/addyosmani/backbone-fundamentals/">improve</a> it.</p>
<p>I'm very pleased to announce that this book will be out in physical form later in the year via <a href="http://oreilly.com">O'Reilly Media</a>. Readers will have the option of purchasing the latest version in either print or a number of digital formats then or can grab a recent version from this repository.</p>
<p>Corrections to existing material are always welcome and I hope that together we can provide the community with an up-to-date resource that is of help. My extended thanks go out to <a href="https://github.com/jashkenas">Jeremy Ashkenas</a> for creating Backbone.js and <a href="https://github.com/addyosmani/backbone-fundamentals/contributors">these</a> members of the community for their assistance tweaking this project.</p>
<p>I hope you find this book helpful!</p>
<p><strong>Notes:</strong></p>
<ul>
<li>Items added or updated in the last month are marked with a * in the outline.</li>
<li>Once you're familiar with Backbone.js, you might be interested in checking out <a href="https://github.com/addyosmani/aura">Aura</a>.</li>
</ul>
<h2 id="table-of-contents">Table Of Contents</h2>
<ul>
<li><h4><a href="#introduction">Introduction</a></h4>
<ul>
<li>MVC, Or Rather MV* Frameworks</li>
<li>What is Backbone.js?</li>
<li>When Do You Need A JavaScript MV* Framework?</li>
<li>When To Consider Using Backbone.js</li>
</ul></li>
<li><h4><a href="#fundamentals">Fundamentals</a></h4>
<ul>
<li><a href="#mvc-mvp">MVC, MVP &amp; Backbone.js</a></li>
</ul></li>
<li><h4><a href="#theinternals">The Internals</a></h4>
<ul>
<li><a href="#thebasics-models">Models</a></li>
<li><a href="#thebasics-views">Views</a></li>
<li><a href="#thebasics-collections">Collections</a></li>
<li><a href="#thebasics-events">Events</a></li>
<li><a href="#thebasics-routers">Routers</a></li>
<li><a href="#thebasics-inheritance">Inheritance &amp; Mixins</a> *</li>
<li><a href="#thebasics-namespacing">Namespacing</a></li>
</ul></li>
<li><h4><a href="#practicaltodos">Practical: Todos - Your First Backbone.js App</a> *</h4></li>
<li><h4><a href="#backboneboilerplate">Backbone Boilerplate &amp; Grunt BBB</a> *</h4></li>
<li><h4><a href="#commonproblems">Common Problems &amp; Solutions</a> *</h4>
<ul>
<li>Sub-Views And Nesting</li>
<li>Managing Models In Nested Views</li>
<li>Views Triggering Other Views</li>
<li>Child Views Rendering Parent Views</li>
<li>Cleanly Disposing Views</li>
<li>Disposing Parent And Child Views</li>
<li>Appending Views</li>
<li>Better Model Property Validation *</li>
</ul></li>
<li><h4><a href="#advanced">Modular Development</a></h4>
<ul>
<li><a href="#modularjs">Introduction</a></li>
<li><a href="#organizingmodules">Organizing modules with Require.js and AMD</a></li>
<li><a href="#externaltemplates">Keeping your templates external</a></li>
<li><a href="#practicalrequirejs">Practical: A Modular App Using AMD &amp; Require.js</a></li>
<li><a href="#optimizingrequirejs">Optimize Apps With The Require.js Optimizer</a></li>
<li><a href="#optimizebuild">Optimize Apps With Require.js Using Packages</a> *</li>
<li><a href="#decouplingbackbone">Decoupling Backbone With The Mediator and Facade patterns</a></li>
</ul></li>
<li><h4><a href="#restfulapps">RESTful Applications With Backbone.js</a></h4>
<ul>
<li><a href="#restful">Building RESTful applications</a></li>
<li><a href="#stack1">Apps With Node.js, Express, Mongoose and MongoDB</a></li>
<li><a href="#stack2">Apps with Ruby, Sinatra, Haml and MongoDB</a></li>
<li><a href="#pagination">Paginating Backbone.js Requests &amp; Collections</a> *</li>
</ul></li>
<li><h4>Mobile Applications</h4>
<ul>
<li>Backbone &amp; jQuery Mobile</li>
<li>Practical: Building A Modular Mobile App With Backbone &amp; jQuery Mobile</li>
</ul></li>
<li><h4><a href="#testing">Unit Testing</a></h4>
<ul>
<li><a href="#unittestingjasmine">Unit Testing Backbone Applications With Jasmine</a></li>
<li>Introduction</li>
<li>Jasmine
<ul>
<li>Suites, Specs And Spies</li>
<li>TDD With Backbone</li>
<li>Testing Models</li>
<li>Testing Collections</li>
<li>Testing Views</li>
</ul></li>
<li><a href="#unittestingqunit">Unit Testing Backbone Applications With QUnit And SinonJS</a></li>
<li>Introduction</li>
<li>QUnit
<ul>
<li>Assertions</li>
<li>Adding structure to assertions</li>
<li>Assertion examples</li>
<li>Fixtures</li>
<li>Asynchronous code</li>
</ul></li>
<li>SinonJS
<ul>
<li>Stubs</li>
<li>Mocks</li>
</ul></li>
<li>Practical
<ul>
<li>Testing Models</li>
<li>Testing Collections</li>
<li>Testing Views</li>
<li>Testing Events</li>
</ul></li>
</ul></li>
<li><h4><a href="#resources">Resources</a></h4></li>
</ul>
<h1 id="introduction"><a name="introduction">Introduction</a></h1>
<p>When writing a Web application from scratch, it’s easy to feel like we can get by simply by relying on a DOM manipulation library (like jQuery) and a handful of utility plugins. The problem with this is that it doesn’t take long to get lost in a nested pile of jQuery callbacks and DOM elements without any real structure in place for our applications.</p>
<p>In short, we’re stuck with spaghetti code. Fortunately there are modern JavaScript frameworks that can assist with bringing structure and organization to our projects, improving how easily maintainable they are in the long-run.</p>
<h3 id="what-is-mvc-or-rather-mv">What Is MVC, Or Rather MV*?</h3>
<p>These modern frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC (Model-View-Controller). MVC separates the concerns in an application down into three parts:</p>
<ul>
<li>Models represent the domain-specific knowledge and data in an application. Think of this as being a ‘type’ of data you can model — like a User, Photo or Note. Models should notify anyone observing them about their current state (e.g Views).</li>
<li>Views are typically considered the User-interface in an application (e.g your markup and templates), but don’t have to be. They should know about the existence of Models in order to observe them, but don’t directly communicate with them.</li>
<li>Controllers handle the input (e.g clicks, user actions) in an application and Views can be considered as handling the output. When a Controller updates the state of a model (such as editing the caption on a Photo), it doesn’t directly tell the View. This is what the observing nature of the View and Model relationship is for.</li>
</ul>
<p>JavaScript ‘MVC’ frameworks that can help us structure our code don’t always strictly follow the above pattern. Some frameworks will include the responsibility of the Controller in the View (e.g Backbone.js) whilst others add their own opinionated components into the mix as they feel this is more effective.</p>
<p>For this reason we refer to such frameworks as following the MV* pattern, that is, you’re likely to have a View and a Model, but more likely to have something else also included.</p>
<h3 id="what-exactly-is-backbone.js">What exactly is Backbone.js?</h3>
<img src="img/backbonejsorg.png" style="margin:0 auto;" width="700px"/>
<p>Backbone.js is a lightweight JavaScript framework for adding structure to your client-side code. It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term.</p>
<p>Developers commonly use frameworks like Backbone.js to create single-page applications or SPAs. To put it simply, these apps enable the browser to react to changes in data on the client-side without the need to completely load up all your markup from the server, meaning no complete page-refreshes are necessary.</p>
<p>Backbone.js is a mature, popular framework at the time of writing and has both a large development community online as well as a wealth of plugins and extensions available to build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and Foursquare.</p>
<h3 id="when-do-you-need-a-javascript-mv-framework">When Do You Need A JavaScript MV* Framework?</h3>
<p>When building a single-page application using JavaScript, whether it involves a complex user interface or is simply trying to reduce the number of HTTP requests required for new Views, you will likely find yourself inventing many of the pieces that make up an MV* framework like Backbone or Ember.</p>
<p>At the outset, it isn’t terribly difficult to write an application framework that offers some opinionated way to avoid spaghetti code, however to say that it is equally as trivial to write something of the standard of Backbone would be a grossly incorrect assumption.</p>
<p>There’s a lot more that goes into structuring an application than tying together a DOM manipulation library, templating and routing. Mature MV* frameworks typically not only include many of the pieces you would find yourself writing, but also include solutions to problems you’ll find yourself running into later on down the road. This is a time-saver that you shouldn’t underestimate the value of.</p>
<p>So, where will you likely need an MV* framework and where won’t you?</p>
<p>If you’re writing an application that will likely only be communicating with an API or back-end data service, where much of the heavy lifting for viewing or manipulating that data will be occurring in the browser, you may find a JavaScript MV* framework useful. Good examples of applications that fall into this category are GMail and Google Docs.</p>
<p>These applications typically download a single payload containing all the scripts, stylesheets and markup users need for common tasks and then perform a lot of additional behavior in the background. It’s trivial to switch between reading an email or document to writing one and you don’t need to ask the application to render the whole page again at all.</p>
<p>If, however, you’re building an application that still relies on the server for most of the heavy-lifting of Views/pages and you’re just using a little JavaScript or jQuery to make things a little more interactive, an MV framework may be overkill. There certainly are complex Web applications where the partial rendering of views can* be coupled with a single-page application effectively, but for everything else, you may find yourself better sticking to a simpler setup.</p>
<p>Maturity in software (framework) development isn't simply about how long a framework has been around. It's about how solid the framework is and more importantly how well it's evolved to fill its role. Has it become more effective at solving common problems? Does it continue to improve as developers build larger and more complex applications with it?</p>
<h3 id="why-should-you-consider-using-backbone.js">Why should you consider using Backbone.js?</h3>
<p>Does the following describe you?:</p>
<p>&quot;I want something flexible which offers a minimalist solution to separating concerns in my application. It should support a persistence layer and RESTful sync, models, views (with controllers), event-driven communication, templating and routing. It should be imperative, allowing one to update the View when a model changes. I’d like some decisions about the architecture left up to me. Ideally, many large companies have used the solution to build non-trivial applications.</p>
<p>As I may be building something complex, I’d like there to be an active extension community around the framework that have already tried addressing larger problems (Marionette, Chaplin, Aura, Thorax). Ideally, there are also scaffolding tools (grunt-bbb, brunch) available for the solution.&quot;</p>
<p>If so, continue reading.</p>
<p>Backbone's main benefits, regardless of your target platform or device, include helping:</p>
<ul>
<li>Organize the structure to your application</li>
<li>Simplify server-side persistence</li>
<li>Decouple the DOM from your page's data</li>
<li>Model data, views and routers in a succinct manner</li>
<li>Provide DOM, model and collection synchronization</li>
</ul>
<h3 id="what-should-you-expect-to-see-in-this-book">What should you expect to see in this book?</h3>
<p>The goal of this book is to create an authoritative and centralized repository of information that can help those developing real-world apps with Backbone. If you come across a section or topic which you think could be improved or expanded on, please feel free to submit a pull-request. It won't take long and you'll be helping other developers avoid problems you've run into before.</p>
<p>Topics will include MVC theory and how to build applications using Backbone's models, views, collections and routers. I'll also be taking you through advanced topics like modular development with Backbone.js and AMD (via Require.js), how to build applications using modern software stacks (like Node and Express), how to solve the routing problems with Backbone and jQuery Mobile, tips about scaffolding tools, and a lot more.</p>
<h1 id="fundamentals"><a name="fundamentals">Fundamentals</a></h1>
<p>In this section, we're going to explore how frameworks like Backbone.js fit in the world of JavaScript application architecture. Classically, developers creating desktop and server-class applications have had a wealth of design patterns available for them to lean on, but it's only been in the past few years that such patterns have come to client-side development.</p>
<p>Before exploring any JavaScript frameworks that assist in structuring applications, it can be useful to gain a basic understanding of architectural design patterns.</p>
<h3 id="mvc-mvp-backbone.js"><a name="mvc-mvp">MVC, MVP &amp; Backbone.js</a></h3>
<p>Design patterns are proven solutions to common development problems and can suggest structural approaches to help guide developers in adding some organization to their applications.</p>
<p>Patterns are useful because they're a set of practices that build upon the collective experience of skilled developers who have repeatedly solved similar problems. Although developers 10 or 20 years ago may not have been using the same programming languages when implementing patterns in their projects, there are many lessons we can learn from their efforts.</p>
<p>In this section, we're going to review two popular patterns - MVC and MVP. We'll be exploring in greater detail how Backbone.js implements these patterns shortly to better appreciate where it fits in.</p>
<h2 id="mvc">MVC</h2>
<p>MVC (Model-View-Controller) is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally present to manage logic, user-input and the coordination of models and views. The pattern was originally designed by <a href="http://en.wikipedia.org/wiki/Trygve_Reenskaug">Trygve Reenskaug</a> while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in <a href="http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612">“Design Patterns: Elements of Reusable Object-Oriented Software”</a> (The &quot;GoF&quot; or “Gang of Four” book) in 1994, which played a role in popularizing its use.</p>
<h3 id="smalltalk-80-mvc">Smalltalk-80 MVC</h3>
<p>It's important to understand what the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70's, graphical user-interfaces were few and far between. An approach known as <a href="http://martinfowler.com/eaaDev/uiArchs.html">Separated Presentation</a> began to be used as a means to make a clear division between domain objects which modeled concepts in the real world (e.g a photo, a person) and the presentation objects which were rendered to the user's screen.</p>
<p>The Smalltalk-80 implementation of MVC took this concept further and had an objective of separating out the application logic from the user interface. The idea was that decoupling these parts of the application would also allow the reuse of models for other interfaces in the application. There are some interesting points worth noting about Smalltalk-80's MVC architecture:</p>
<ul>
<li>A Domain element was known as a Model and were ignorant of the user-interface (Views and Controllers)</li>
<li>Presentation was taken care of by the View and the Controller, but there wasn't just a single view and controller. A View-Controller pair was required for each element being displayed on the screen and so there was no true separation between them</li>
<li>The Controller's role in this pair was handling user input (such as key-presses and click events), doing something sensible with them.</li>
<li>The Observer pattern was relied upon for updating the View whenever the Model changed</li>
</ul>
<p>Developers are sometimes surprised when they learn that the Observer pattern (nowadays commonly implemented as a Publish/Subscribe system) was included as a part of MVC's architecture decades ago. In Smalltalk-80's MVC, the View and Controller both observe the Model: anytime the Model changes, the Views react. A simple example of this is an application backed by stock market data - for the application to show real-time information, any change to the data in its Models should result in the View being refreshed instantly.</p>
<p>Martin Fowler has done an excellent job of writing about the <a href="http://martinfowler.com/eaaDev/uiArchs.html">origins</a> of MVC over the years and if you are interested in further historical information about Smalltalk-80's MVC, I recommend reading his work.</p>
<h2 id="mvc-as-we-know-it">MVC As We Know It</h2>
<p>We've reviewed the 70's, but let us now return to the here and now. The MVC pattern has been applied to a diverse range of programming languages. For example, the popular Ruby on Rails is an implementation of a web application framework based on MVC for the Ruby language. JavaScript now has a number of MVC frameworks, including Ember.js, JavaScriptMVC, and of course Backbone.js. Given the importance of avoiding &quot;spaghetti&quot; code, a term which describes code that is very difficult to read or maintain due to its lack of structure, let's look at what the MVC pattern enables the Javascript developer to do.</p>
<p>MVC is composed of three core components:</p>
<h3 id="models">Models</h3>
<p>Models manage the data for an application. They are concerned with neither the user-interface nor presentation layers, but instead represent structured data that an application may require. When a model changes (e.g when it is updated), it will typically notify its observers (e.g views, a concept we will cover shortly) that a change has occurred so that they may react accordingly.</p>
<p>To understand models better, let us imagine we have a JavaScript photo gallery application. In a photo gallery, a photo would merit its own model, as it represents a unique kind of domain-specific data. The Photo model may represent attributes such as a caption, image source and additional meta-data. A specific photo would be stored in an instance of a model. Here's an example of a simple Photo model implemented with Backbone.js:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({

    <span class="co">// Default attributes for the photo</span>
    <span class="dt">defaults</span>: {
      <span class="co">// Ensure that each photo created has an `src`.</span>
      <span class="dt">src</span>: <span class="st">&quot;placeholder.jpg&quot;</span>,
      <span class="dt">caption</span>: <span class="st">&quot;A default image&quot;</span>,
      <span class="dt">viewed</span>: <span class="kw">false</span>
    },

    <span class="dt">initialize</span>: <span class="kw">function</span>() {
    }

});</code></pre>
<p>The built-in capabilities of models vary across frameworks, however it's common for them to support validation of attributes, where attributes represent the properties of the model, such as a model identifier. When using models in real-world applications we generally also need a way of persisting models. Persistence allows us to edit and update models with the knowledge that their most recent states will be saved somewhere, for example in a web browser's localStorage data-store or synchronized with a database.</p>
<p>A model may also have multiple views observing it. Imagine our Photo model contained meta-data such as the longitude and latitude where the photo was taken, a list of people present in the photo, and a list of tags. A developer could create a single view that displayed all these attributes, or might create three separate views to display each attribute. The important detail is that the Photo model doesn't care how these views are organized, it simply announces updates to its data as necessary. We'll come back to Views in more detail later.</p>
<p>It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together. In Backbone, these groups are called &quot;Collections&quot;. Managing models in groups allows us to write application logic based on notifications from the group, should any model it contains change. This avoids the need to manually observe individual model instances.</p>
<p>Here's how we might group Photo models into a simplified Backbone Collection:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoGallery = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({

    <span class="co">// Reference to this collection&#39;s model.</span>
    <span class="dt">model</span>: Photo,

    <span class="co">// Filter down the list of all photos that have been viewed</span>
    <span class="dt">viewed</span>: <span class="kw">function</span>() {
      <span class="kw">return</span> <span class="kw">this</span>.<span class="fu">filter</span>(<span class="kw">function</span>(photo){ <span class="kw">return</span> <span class="kw">photo</span>.<span class="fu">get</span>(<span class="ch">&#39;viewed&#39;</span>); });
    },

    <span class="co">// Filter down the list to only photos that have not yet been viewed</span>
    <span class="dt">unviewed</span>: <span class="kw">function</span>() {
      <span class="kw">return</span> <span class="kw">this</span>.<span class="fu">without</span>.<span class="fu">apply</span>(<span class="kw">this</span>, <span class="kw">this</span>.<span class="fu">viewed</span>());
    }

});</code></pre>
<p>If you read older texts on MVC, you may come across a description of models as also managing application 'state'. In JavaScript applications &quot;state&quot; has a specific meaning, typically referring to the current &quot;state&quot; of a view or sub-view on a user's screen at a fixed time. State is a topic which is regularly discussed when looking at Single-page applications, where the concept of state needs to be simulated.</p>
<h3 id="views">Views</h3>
<p>Views are a visual representation of models that present a filtered view of their current state. A view typically observes a model and is notified when the model changes, allowing the view to update itself accordingly. Design pattern literature commonly refers to views as 'dumb', given that their knowledge of models and controllers in an application is limited.</p>
<p>Users interact with views, which usually means reading and editing model data. For example, in our photo gallery application example, model viewing might happen in a user interface with a big image, a caption, and a list of tags. Model editing could be done through an &quot;edit&quot; view where a user who has selected a specific photo could edit its caption, tags, or other metadata in a form.</p>
<p>In MVC, the actual task of updating the Model falls to Controllers, which we'll be covering shortly.</p>
<p>Let's explore Views a little further using a simple JavaScript example. Below we can see a function that creates a single Photo view, consuming both a model instance and a controller instance.</p>
<p>We define a <code>render()</code> utility within our view which is responsible for rendering the contents of the <code>photoModel</code> using a JavaScript templating engine (<a href="http://underscorejs.org" title="Underscore.js">Underscore</a> templating) and updating the contents of our view, referenced by <code>photoEl</code>.</p>
<p>The <code>photoModel</code> then adds our <code>render()</code> callback as one of its subscribers, so that through the Observer pattern it can trigger the view to update when the model changes.</p>
<p>You may wonder where user interaction comes into play here. When users click on any elements within the view, it's not the view's responsibility to know what to do next. A Controller makes this decision. In our sample implementation, this is achieved by adding an event listener to <code>photoEl</code> which will delegate handling the click behavior back to the controller, passing the model information along with it in case it's needed.</p>
<p>The benefit of this architecture is that each component plays its own separate role in making the application function as needed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> buildPhotoView = <span class="kw">function</span>( photoModel, photoController ){

    <span class="kw">var</span> base = <span class="kw">document</span>.<span class="fu">createElement</span>(<span class="ch">&#39;div&#39;</span>),
        photoEl = <span class="kw">document</span>.<span class="fu">createElement</span>(<span class="ch">&#39;div&#39;</span>);

     <span class="kw">base</span>.<span class="fu">appendChild</span>(photoEl);

     <span class="kw">var</span> render= <span class="kw">function</span>(){
        <span class="co">// We use a templating library such as Underscore</span>
        <span class="co">// templating which generates the HTML for our</span>
        <span class="co">// photo entry</span>
        <span class="kw">photoEl</span>.<span class="fu">innerHTML</span> = <span class="kw">_</span>.<span class="fu">template</span>(<span class="ch">&#39;photoTemplate&#39;</span>, {<span class="dt">src</span>: <span class="kw">photoModel</span>.<span class="fu">getSrc</span>()});
     }

     <span class="kw">photoModel</span>.<span class="fu">addSubscriber</span>( render );

     <span class="kw">photoEl</span>.<span class="fu">addEventListener</span>(<span class="ch">&#39;click&#39;</span>, <span class="kw">function</span>(){
        <span class="kw">photoController</span>.<span class="fu">handleEvent</span>(<span class="ch">&#39;click&#39;</span>, photoModel );
     });

     <span class="kw">var</span> show = <span class="kw">function</span>(){
        <span class="kw">photoEl.style</span>.<span class="fu">display</span> = <span class="ch">&#39;&#39;</span>;
     }

     <span class="kw">var</span> hide = <span class="kw">function</span>(){
        <span class="kw">photoEl.style</span>.<span class="fu">display</span> = <span class="ch">&#39;none&#39;</span>;
     }


     <span class="kw">return</span>{
        <span class="dt">showView</span>: show,
        <span class="dt">hideView</span>: hide
     }

}</code></pre>
<p><strong>Templating</strong></p>
<p>In the context of JavaScript frameworks that support MVC/MV*, it is worth looking more closely at JavaScript templating and its relationship to Views.</p>
<p>It has long been considered bad practice (and computationally expensive) to manually create large blocks of HTML markup in-memory through string concatenation. Developers using this technique often find themselves iterating through their data, wrapping it in nested divs and using outdated techniques such as <code>document.write</code> to inject the 'template' into the DOM. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications.</p>
<p>JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to define templates for views as HTML markup containing template variables. These template blocks can be either stored externally or within script tags with a custom type (e.g 'text/template'). Variables are delimited using a variable syntax (e.g {{name}}). Javascript template libraries typically accept data in JSON, and the grunt work of populating templates with data is taken care of by the framework itself. This has a several benefits, particularly when opting to store templates externally as this can let applications load templates dynamically on an as-needed basis.</p>
<p>Let's compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore's 'microtemplates'.</p>
<p><strong>Handlebars.js:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;li</span><span class="ot"> class=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;h2&gt;</span>{{caption}}<span class="kw">&lt;/h2&gt;</span>
  <span class="kw">&lt;img</span><span class="ot"> class=</span><span class="st">&quot;source&quot;</span><span class="ot"> src=</span><span class="st">&quot;{{src}}&quot;</span><span class="kw">/&gt;</span>
  <span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;meta-data&quot;</span><span class="kw">&gt;</span>
    {{metadata}}
  <span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;/li&gt;</span></code></pre>
<p><strong>Underscore.js Microtemplates:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;li</span><span class="ot"> class=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;h2&gt;</span><span class="er">&lt;</span>%= caption %&gt;<span class="kw">&lt;/h2&gt;</span>
  <span class="kw">&lt;img</span><span class="ot"> class=</span><span class="st">&quot;source&quot;</span><span class="ot"> src=</span><span class="st">&quot;</span><span class="er">&lt;</span><span class="st">%= src %&gt;&quot;</span><span class="kw">/&gt;</span>
  <span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;meta-data&quot;</span><span class="kw">&gt;</span>
    <span class="er">&lt;</span>%= metadata %&gt;
  <span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;/li&gt;</span></code></pre>
<p>You may also use double curly brackets (i.e <code>{{}}</code>) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore <code>templateSettings</code> attribute as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">_</span>.<span class="fu">templateSettings</span> = { <span class="dt">interpolate </span>: <span class="ot">/</span><span class="fl">\{\{(</span><span class="ot">.</span><span class="fl">+?)\}\}</span><span class="ot">/g</span> };</code></pre>
<p><strong>A note on navigation and state</strong></p>
<p>It is also worth noting that in classical web development, navigating between independent views required the use of a page refresh. In single-page JavaScript applications, however, once data is fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. Since this doesn't automatically update the URL, the role of navigation thus falls to a &quot;router&quot;, which assists in managing application state (e.g allowing users to bookmark a particular view they have navigated to). As routers are however neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section.</p>
<h3 id="controllers">Controllers</h3>
<p>Controllers are an intermediary between models and views which are classically responsible for two tasks: they both update the view when the model changes and update the model when the user manipulates the view.</p>
<p>In our photo gallery application, a controller would be responsible for handling changes the user made to the edit view for a particular photo, updating a specific photo model when a user has finished editing.</p>
<p>It's with controllers that most JavaScript MVC frameworks depart from this interpretation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript framework authors likely initially looked at server-side interpretations of MVC (such as Ruby on Rails), realized that that approach didn't translate 1:1 on the client-side, and so re-interpreted the C in MVC to solve their state management problem. This was a clever approach, but it can make it hard for developers coming to MVC for the first time to understand both the classical MVC pattern and the &quot;proper&quot; role of controllers in other non-Javascript frameworks.</p>
<p>So does Backbone.js have Controllers? Not really. Backbone's Views typically contain &quot;controller&quot; logic, and Routers (discussed below) are used to help manage application state, but neither are true Controllers according to classical MVC.</p>
<p>In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It's in fact better to see it a member of the MV* family which approaches architecture in its own way. There is of course nothing wrong with this, but it is important to distinguish between classical MVC and MV* should you be relying on discussions of MVC to help with your Backbone projects.</p>
<h3 id="controllers-in-spine.js-vs-backbone.js">Controllers in Spine.js vs Backbone.js</h3>
<p><strong>Spine.js</strong></p>
<p>We now know that controllers are traditionally responsible for updating the view when the model changes (and similarly the model when the user updates the view). Since Backbone doesn't have its <strong>own</strong> explicit controllers, it's useful to review the controller from another MVC framework to appreciate the difference in implementations. Let's take a look at <a href="http://spinejs.com/">Spine.js</a>:</p>
<p>In this example, we're going to have a controller called <code>PhotosController</code> which will be in charge of individual photos in the application. It will ensure that when the view updates (e.g a user edited the photo meta-data) the corresponding model does too.</p>
<p>(Note: We won't be delving heavily into Spine.js beyond this example, but it's worth looking at it to learn more about Javascript frameworks in general.)</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Controllers in Spine are created by inheriting from Spine.Controller</span>

<span class="kw">var</span> PhotosController = <span class="kw">Spine.Controller</span>.<span class="fu">sub</span>({
  <span class="dt">init</span>: <span class="kw">function</span>(){
    <span class="kw">this</span>.<span class="fu">item</span>.<span class="fu">bind</span>(<span class="st">&quot;update&quot;</span>, <span class="kw">this</span>.<span class="fu">proxy</span>(<span class="kw">this</span>.<span class="fu">render</span>));
    <span class="kw">this</span>.<span class="fu">item</span>.<span class="fu">bind</span>(<span class="st">&quot;destroy&quot;</span>, <span class="kw">this</span>.<span class="fu">proxy</span>(<span class="kw">this</span>.<span class="fu">remove</span>));
  },

  <span class="dt">render</span>: <span class="kw">function</span>(){
    <span class="co">// Handle templating</span>
    <span class="kw">this</span>.<span class="fu">replace</span>($(<span class="st">&quot;#photoTemplate&quot;</span>).<span class="fu">tmpl</span>(<span class="kw">this</span>.<span class="fu">item</span>));
    <span class="kw">return</span> <span class="kw">this</span>;
  },

  <span class="dt">remove</span>: <span class="kw">function</span>(){
    <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">remove</span>();
    <span class="kw">this</span>.<span class="fu">release</span>();
  }
});</code></pre>
<p>In Spine, controllers are considered the glue for an application, adding and responding to DOM events, rendering templates and ensuring that views and models are kept in sync (which makes sense in the context of what we know to be a controller).</p>
<p>What we're doing in the above example is setting up listeners in the <code>update</code> and <code>destroy</code> events using <code>render()</code> and <code>remove()</code>. When a photo entry gets updated, we re-render the view to reflect the changes to the meta-data. Similarly, if the photo gets deleted from the gallery, we remove it from the view. In case you were wondering about the <code>tmpl()</code> function in the code snippet: in the <code>render()</code> function, we're using this to render a JavaScript template called #photoTemplate which simply returns an HTML string used to replace the controller's current element.</p>
<p>What this provides us with is a very lightweight, simple way to manage changes between the model and the view.</p>
<p><strong>Backbone.js</strong></p>
<p>Later on in this section we're going to revisit the differences between Backbone and traditional MVC, but for now let's focus on controllers.</p>
<p>In Backbone, controller logic is shared between Backbone.View and Backbone.Router. Earlier releases of Backbone contained something called Backbone.Controller, but it was renamed to Router to clarify its role.</p>
<p>A Router's main purpose is to translate URL requests into application states. When a user browses to the URL www.example.com/photos/42, a Router could be used to show the photo with that ID, and to define what application behavior should be run in response to that request. Routers <em>can</em> contain traditional controller responsibilities, such as binding the events between models and views, or rendering parts of the page. However, Backbone contributor Tim Branyen has pointed out that it's possible to get away without needing Backbone.Router at all for this, so a way to think about it using the Router paradigm is probably:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
  <span class="dt">routes</span>: { <span class="st">&quot;photos/:id&quot;</span>: <span class="st">&quot;route&quot;</span> },

  <span class="dt">route</span>: <span class="kw">function</span>(id) {
    <span class="kw">var</span> item = <span class="kw">photoCollection</span>.<span class="fu">get</span>(id);
    <span class="kw">var</span> view = <span class="kw">new</span> PhotoView({ <span class="dt">model</span>: item });

    <span class="kw">something</span>.<span class="fu">html</span>( <span class="kw">view</span>.<span class="fu">render</span>().<span class="fu">el</span> );
  }
}):</code></pre>
<h2 id="what-does-mvc-give-us">What does MVC give us?</h2>
<p>To summarize, the separation of concerns in MVC facilitates modularization of an application's functionality and enables:</p>
<ul>
<li>Easier overall maintenance. When updates need to be made to the application it is clear whether the changes are data-centric, meaning changes to models and possibly controllers, or merely visual, meaning changes to views.</li>
<li>Decoupling models and views means that it's straight-forward to write unit tests for business logic</li>
<li>Duplication of low-level model and controller code is eliminated across the application</li>
<li>Depending on the size of the application and separation of roles, this modularity allows developers responsible for core logic and developers working on the user-interfaces to work simultaneously</li>
</ul>
<h3 id="delving-deeper">Delving deeper</h3>
<p>Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we'll explore it a little further.</p>
<p>The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a &quot;set of classes to build a user interface&quot;. In their view, it's actually a variation of three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I've covered some of these patterns in my other free book, JavaScript Design Patterns For Beginners if you would like to read into them further.</p>
<p>As we've discussed, models represent application data, while views handle what the user is presented on screen. As such, MVC relies on Pub/Sub for some of its core communication (something that surprisingly isn't covered in many articles about the MVC pattern). When a model is changed it &quot;publishes&quot; to the rest of the application that it has been updated. The &quot;subscriber&quot;--generally a Controller--then updates the view accordingly. The observer-viewer nature of this relationship is what facilitates multiple views being attached to the same model.</p>
<p>For developers interested in knowing more about the decoupled nature of MVC (once again, depending on the implementation), one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and controllers have a slightly different relationship. Controllers facilitate views to respond to different user input and are an example of the Strategy pattern.</p>
<h3 id="summary">Summary</h3>
<p>Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern.</p>
<p>When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it's opted to approach Models, Views, Controllers or other alternatives, as this can better help you grok how the framework expects to be used.</p>
<h2 id="mvp">MVP</h2>
<p>Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named <a href="http://en.wikipedia.org/wiki/Taligent">Taligent</a> in the early 1990s while they were working on a model for a C++ CommonPoint environment. Whilst both MVC and MVP target the separation of concerns across multiple components, there are some fundamental differences between them.</p>
<p>For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures.</p>
<h3 id="models-views-presenters">Models, Views &amp; Presenters</h3>
<p>The P in MVP stands for presenter. It's a component which contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things such as being able to mock views in unit tests.</p>
<p>The most common implementation of MVP is one which uses a Passive View (a view which is for all intents and purposes &quot;dumb&quot;), containing little to no logic. MVP models are almost identical to MVC models and handle application data. The presenter acts as a mediator which talks to both the view and model, however both of these are isolated from each other. They effectively bind models to views, a responsibility held by Controllers in MVC. Presenters are at the heart of the MVP pattern and as you can guess, incorporate the presentation logic behind views.</p>
<p>Solicited by a view, presenters perform any work to do with user requests and pass data back to them. In this respect, they retrieve data, manipulate it and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events but it's the presenter's role to subscribe to them so that it can update the view. In this passive architecture, we have no concept of direct data binding. Views expose setters which presenters can use to set data.</p>
<p>The benefit of this change from MVC is that it increases the testability of your application and provides a more clean separation between the view and the model. This isn't however without its costs as the lack of data binding support in the pattern can often mean having to take care of this task separately.</p>
<p>Although a common implementation of a <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a> is for the view to implement an interface, there are variations on it, including the use of events which can decouple the View from the Presenter a little more. As we don't have the interface construct in JavaScript, we're using it more and more a protocol than an explicit interface here. It's technically still an API and it's probably fair for us to refer to it as an interface from that perspective.</p>
<p>There is also a <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a> variation of MVP, which is closer to the MVC and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey's Backbone.ModelBinding plugin) introduce this idea of a Supervising Controller to Backbone.</p>
<h2 id="mvp-or-mvc">MVP or MVC?</h2>
<p>MVP is generally used most often in enterprise-level applications where it's necessary to reuse as much presentation logic as possible. Applications with very complex views and a great deal of user interaction may find that MVC doesn't quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. In MVP, all of this complex logic can be encapsulated in a presenter, which can simplify maintenance greatly.</p>
<p>As MVP views are defined through an interface and the interface is technically the only point of contact between the system and the view (other than a presenter), this pattern also allows developers to write presentation logic without needing to wait for designers to produce layouts and graphics for the application.</p>
<p>Depending on the implementation, MVP may be more easy to automatically unit test than MVC. The reason often cited for this is that the presenter can be used as a complete mock of the user-interface and so it can be unit tested independent of other components. In my experience this really depends on the languages you are implementing MVP in (there's quite a difference between opting for MVP for a JavaScript project over one for say, ASP.NET).</p>
<p>At the end of the day, the underlying concerns you may have with MVC will likely hold true for MVP given that the differences between them are mainly semantic. As long as you are cleanly separating concerns into models, views and controllers (or presenters) you should be achieving most of the same benefits regardless of the pattern you opt for.</p>
<h2 id="mvc-mvp-and-backbone.js">MVC, MVP and Backbone.js</h2>
<p>There are very few, if any architectural JavaScript frameworks that claim to implement the MVC or MVP patterns in their classical form as many JavaScript developers don't view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.NET or GWT). This is because it's possible to have additional presenter/view logic in your application and yet still consider it a flavor of MVC.</p>
<p>Backbone contributor <a href="http://ireneros.com/">Irene Ros</a> subscribes to this way of thinking as when she separates Backbone views out into their own distinct components, she needs something to actually assemble them for her. This could either be a controller route (such as a <code>Backbone.Router</code>, covered later in the book) or a callback in response to data being fetched.</p>
<p>That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC . Their view is that:</p>
<ul>
<li>The presenter in MVP better describes the <code>Backbone.View</code> (the layer between View templates and the data bound to it) than a controller does</li>
<li>The model fits <code>Backbone.Model</code> (it isn't that different from the classical MVC &quot;Model&quot;)</li>
<li>The views best represent templates (e.g Handlebars/Mustache markup templates)</li>
</ul>
<p>A response to this could be that the view can also just be a View (as per MVC) because Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and the P in MVP can both be accomplished by <code>Backbone.View</code> because they're able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.</p>
<p>We've also seen that in Backbone the responsibility of a controller is shared with both the Backbone.View and Backbone.Router and in the following example we can actually see that aspects of that are certainly true.</p>
<p>Here, our Backbone <code>PhotoView</code> uses the Observer pattern to 'subscribe' to changes to a View's model in the line <code>this.model.on('change',...)</code>. It also handles templating in the <code>render()</code> method, but unlike some other implementations, user interaction is also handled in the View (see <code>events</code>).</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({

    <span class="co">//... is a list tag.</span>
    <span class="dt">tagName</span>: <span class="st">&quot;li&quot;</span>,

    <span class="co">// Pass the contents of the photo template through a templating</span>
    <span class="co">// function, cache it for a single photo</span>
    <span class="dt">template</span>: <span class="kw">_</span>.<span class="fu">template</span>($(<span class="ch">&#39;#photo-template&#39;</span>).<span class="fu">html</span>()),

    <span class="co">// The DOM events specific to an item.</span>
    <span class="dt">events</span>: {
      <span class="st">&quot;click img&quot;</span> : <span class="st">&quot;toggleViewed&quot;</span>
    },

    <span class="co">// The PhotoView listens for changes to its model, re-rendering. Since there&#39;s</span>
    <span class="co">// a one-to-one correspondence between a **Photo** and a **PhotoView** in this</span>
    <span class="co">// app, we set a direct reference on the model for convenience.</span>

    <span class="dt">initialize</span>: <span class="kw">function</span>() {
      <span class="kw">_</span>.<span class="fu">bindAll</span>(<span class="kw">this</span>, <span class="ch">&#39;render&#39;</span>);
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>(<span class="ch">&#39;change&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>);
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>(<span class="ch">&#39;destroy&#39;</span>, <span class="kw">this</span>.<span class="fu">remove</span>);
    },

    <span class="co">// Re-render the photo entry</span>
    <span class="dt">render</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">template</span>(<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>()));
      <span class="kw">return</span> <span class="kw">this</span>;
    },

    <span class="co">// Toggle the `&quot;viewed&quot;` state of the model.</span>
    <span class="dt">toggleViewed</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">viewed</span>();
    }

});</code></pre>
<p>Another (quite different) opinion is that Backbone more closely resembles <a href="http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController">Smalltalk-80 MVC</a>, which we went through earlier.</p>
<p>As regular Backbone user Derick Bailey has <a href="http://lostechies.com/derickbailey/2011/12/23/backbone-js-is-not-an-mvc-framework/">written</a>, it's ultimately best not to force Backbone to fit any specific design patterns. Design patterns should be considered flexible guides to how applications may be structured and in this respect, Backbone doesn't fit either MVC nor MVP perfectly. Instead, it borrows some of the best concepts from multiple architectural patterns and creates a flexible framework that just works well. Call it <strong>the Backbone way</strong>, MV* or whatever helps reference its flavor of application architecture.</p>
<p>It <em>is</em> however worth understanding where and why these concepts originated, so I hope that my explanations of MVC and MVP have been of help. Most structural JavaScript frameworks will adopt their own take on classical patterns, either intentionally or by accident, but the important thing is that they help us develop applications which are organized, clean and can be easily maintained.</p>
<h2 id="fast-facts">Fast facts</h2>
<h3 id="backbone.js">Backbone.js</h3>
<ul>
<li>Core components: Model, View, Collection, Router. Enforces its own flavor of MV*</li>
<li>Good documentation, with more improvements on the way</li>
<li>Used by large companies such as SoundCloud and Foursquare to build non-trivial applications</li>
<li>Event-driven communication between views and models. As we'll see, it's relatively straight-forward to add event listeners to any attribute in a model, giving developers fine-grained control over what changes in the view</li>
<li>Supports data bindings through manual events or a separate Key-value observing (KVO) library</li>
<li>Great support for RESTful interfaces out of the box, so models can be easily tied to a backend</li>
<li>Extensive eventing system. It's <a href="http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/">trivial</a> to add support for pub/sub in Backbone</li>
<li>Prototypes are instantiated with the <code>new</code> keyword, which some developers prefer</li>
<li>Agnostic about templating frameworks, however Underscore's micro-templating is available by default. Backbone works well with libraries like Handlebars</li>
<li>Doesn't support deeply nested models, though there are Backbone plugins such as <a href="https://github.com/PaulUithol/Backbone-relational">this</a> which can help</li>
<li>Clear and flexible conventions for structuring applications. Backbone doesn't force usage of all of its components and can work with only those needed.</li>
</ul>
<h1 id="the-internals"><a name="theinternals">The Internals</a></h1>
<p>In this section, you'll learn the essentials of Backbone's models, views, collections and routers, as well as about using namespacing to organize your code. This isn't meant as a replacement for the official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications with it.</p>
<ul>
<li>Models</li>
<li>Collections</li>
<li>Routers</li>
<li>Views</li>
<li>Namespacing</li>
</ul>
<h2 id="models-1"><a name="thebasics-models" id="thebasics-models">Models</a></h2>
<p>Backbone models contain interactive data for an application as well as the logic around this data. For example, we can use a model to represent the concept of a photo object including its attributes like tags, titles and a location.</p>
<p>Models can be created by extending <code>Backbone.Model</code> as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
    <span class="dt">defaults</span>: {
        <span class="dt">src</span>: <span class="ch">&#39;placeholder.jpg&#39;</span>,
        <span class="dt">title</span>: <span class="ch">&#39;an image placeholder&#39;</span>,
        <span class="dt">coordinates</span>: [<span class="dv">0</span>,<span class="dv">0</span>]
    },
    <span class="dt">initialize</span>: <span class="kw">function</span>(){
        <span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&quot;change:src&quot;</span>, <span class="kw">function</span>(){
            <span class="kw">var</span> src = <span class="kw">this</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>);
            <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Image source updated to &#39;</span> + src);
        });
    },
    <span class="dt">changeSrc</span>: <span class="kw">function</span>( source ){
        <span class="kw">this</span>.<span class="fu">set</span>({ <span class="dt">src</span>: source });
    }
});

<span class="kw">var</span> somePhoto = <span class="kw">new</span> Photo({ <span class="dt">src</span>: <span class="st">&quot;test.jpg&quot;</span>, <span class="dt">title</span>:<span class="st">&quot;testing&quot;</span>});
<span class="kw">somePhoto</span>.<span class="fu">changeSrc</span>(<span class="st">&quot;magic.jpg&quot;</span>); <span class="co">// which triggers &quot;change:src&quot; and logs an update message to the console.</span></code></pre>
<h4 id="initialization">Initialization</h4>
<p>The <code>initialize()</code> method is called when a new instance of a model is created. Its use is optional, however you'll see why it's good practice to use it below.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
    <span class="dt">initialize</span>: <span class="kw">function</span>(){
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
    }
});

<span class="co">// We can then create our own instance of a photo as follows:</span>
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo();</code></pre>
<h4 id="getters-setters">Getters &amp; Setters</h4>
<p><strong>Model.get()</strong></p>
<p><code>Model.get()</code> provides easy access to a model's attributes. Attributes which are passed through to the model on instantiation are instantly available for retrieval.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">title</span>: <span class="st">&quot;My awesome photo&quot;</span>,
                          <span class="dt">src</span>:<span class="st">&quot;boston.jpg&quot;</span>,
                          <span class="dt">location</span>: <span class="st">&quot;Boston&quot;</span>,
                          <span class="dt">tags</span>:[<span class="ch">&#39;the big game&#39;</span>, <span class="ch">&#39;vacation&#39;</span>]}),

    title = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>), <span class="co">//My awesome photo</span>
    location = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;location&quot;</span>), <span class="co">//Boston</span>
    tags = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;tags&quot;</span>), <span class="co">// [&#39;the big game&#39;,&#39;vacation&#39;]</span>
    photoSrc = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>); <span class="co">//boston.jpg</span></code></pre>
<p>Alternatively, if you wish to directly access all of the attributes in a model's instance directly, you can achieve this as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myAttributes = <span class="kw">myPhoto</span>.<span class="fu">attributes</span>;
<span class="kw">console</span>.<span class="fu">log</span>(myAttributes);</code></pre>
<p>It is best practice to use <code>Model.set()</code> or direct instantiation to set the values of a model's attributes.</p>
<p>Accessing <code>Model.attributes</code> directly is generally discouraged. Instead, should you need to read or clone data, <code>Model.toJSON()</code> is recommended for this purpose. If you would like to access or copy a model's attributes for purposes such as JSON stringification (e.g. for serialization prior to being passed to a view), this can be achieved using Model.toJSON(). Remember that this will return an object and JSON.stringify() should be used to get a string representation of the data:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myAttributes = <span class="kw">myPhoto</span>.<span class="fu">toJSON</span>();
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">JSON</span>.<span class="fu">stringify</span>(myattributes));
<span class="co">/* this returns:</span>
<span class="co"> { title: &quot;My awesome photo&quot;,</span>
<span class="co"> src:&quot;boston.jpg&quot;,</span>
<span class="co"> location: &quot;Boston&quot;,</span>
<span class="co"> tags:[&#39;the big game&#39;, &#39;vacation&#39;]}</span>
<span class="co">*/</span></code></pre>
<h4 id="model.set">Model.set()</h4>
<p><code>Model.set()</code> allows us to pass attributes into an instance of our model. Attributes can either be set during initialization or at any time afterwards. It's important to avoid trying to set a Model's attributes directly (for example, <code>Model.caption = 'A new caption'</code>). Backbone uses Model.set() to know when to broadcast that a model's data has changed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
    <span class="dt">initialize</span>: <span class="kw">function</span>(){
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
    }
});

<span class="co">// Setting the value of attributes via instantiation</span>
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">title</span>: <span class="ch">&#39;My awesome photo&#39;</span>, <span class="dt">location</span>: <span class="ch">&#39;Boston&#39;</span> });

<span class="kw">var</span> myPhoto2 = <span class="kw">new</span> Photo();

<span class="co">// Setting the value of attributes through Model.set()</span>
<span class="kw">myPhoto2</span>.<span class="fu">set</span>({ <span class="dt">title</span>:<span class="ch">&#39;Vacation in Florida&#39;</span>, <span class="dt">location</span>: <span class="ch">&#39;Florida&#39;</span> });</code></pre>
<p><strong>Default values</strong></p>
<p>There are times when you want your model to have a set of default values (e.g. in a scenario where a complete set of data isn't provided by the user). This can be set using a property called <code>defaults</code> in your model.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
    <span class="dt">defaults</span>: {
        <span class="dt">title</span>: <span class="ch">&#39;Another photo!&#39;</span>,
        <span class="dt">tags</span>: [<span class="ch">&#39;untagged&#39;</span>],
        <span class="dt">location</span>: <span class="ch">&#39;home&#39;</span>,
        <span class="dt">src</span>: <span class="ch">&#39;placeholder.jpg&#39;</span>
    },
    <span class="dt">initialize</span>: <span class="kw">function</span>(){
    }
});

<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">location</span>: <span class="st">&quot;Boston&quot;</span>,
                          <span class="dt">tags</span>:[<span class="ch">&#39;the big game&#39;</span>, <span class="ch">&#39;vacation&#39;</span>]}),
    title = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>), <span class="co">//Another photo!</span>
    location = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;location&quot;</span>), <span class="co">//Boston</span>
    tags = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;tags&quot;</span>), <span class="co">// [&#39;the big game&#39;,&#39;vacation&#39;]</span>
    photoSrc = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>); <span class="co">//placeholder.jpg</span></code></pre>
<p><strong>Listening for changes to your model</strong></p>
<p>Any and all of the attributes in a Backbone model can have listeners bound to them which detect when their values change. Listeners can be added to the <code>initialize()</code> function:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">this</span>.<span class="fu">on</span>(<span class="ch">&#39;change&#39;</span>, <span class="kw">function</span>(){
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;values for this model have changed&#39;</span>);
});</code></pre>
<p>In the following example, we log a message whenever a specific attribute (the title of our Photo model) is altered.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
    <span class="dt">defaults</span>: {
        <span class="dt">title</span>: <span class="ch">&#39;Another photo!&#39;</span>,
        <span class="dt">tags</span>: [<span class="ch">&#39;untagged&#39;</span>],
        <span class="dt">location</span>: <span class="ch">&#39;home&#39;</span>,
        <span class="dt">src</span>: <span class="ch">&#39;placeholder.jpg&#39;</span>
    },
    <span class="dt">initialize</span>: <span class="kw">function</span>(){
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
        <span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&quot;change:title&quot;</span>, <span class="kw">function</span>(){
            <span class="kw">var</span> title = <span class="kw">this</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>);
            <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;My title has been changed to.. &quot;</span> + title);
        });
    },

    <span class="dt">setTitle</span>: <span class="kw">function</span>(newTitle){
        <span class="kw">this</span>.<span class="fu">set</span>({ <span class="dt">title</span>: newTitle });
    }
});

<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">title</span>:<span class="st">&quot;Fishing at the lake&quot;</span>, <span class="dt">src</span>:<span class="st">&quot;fishing.jpg&quot;</span>});
<span class="kw">myPhoto</span>.<span class="fu">setTitle</span>(<span class="ch">&#39;Fishing at sea&#39;</span>);
<span class="co">//logs &#39;My title has been changed to.. Fishing at sea&#39;</span></code></pre>
<p><strong>Validation</strong></p>
<p>Backbone supports model validation through <code>Model.validate()</code>, which allows checking the attribute values for a model prior to them being set.</p>
<p>Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from <code>.validate()</code>. If they are invalid, a custom error can be returned instead.</p>
<p>A basic example for validation can be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
    <span class="dt">validate</span>: <span class="kw">function</span>(attribs){
        <span class="kw">if</span>(<span class="kw">attribs</span>.<span class="fu">src</span> === undefined){
            <span class="kw">return</span> <span class="st">&quot;Remember to set a source for your image!&quot;</span>;
        }
    },

    <span class="dt">initialize</span>: <span class="kw">function</span>(){
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
        <span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&quot;error&quot;</span>, <span class="kw">function</span>(model, error){
            <span class="kw">console</span>.<span class="fu">log</span>(error);
        });
    }
});

<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo();
<span class="kw">myPhoto</span>.<span class="fu">set</span>({ <span class="dt">title</span>: <span class="st">&quot;On the beach&quot;</span> });
<span class="co">//logs Remember to set a source for your image!</span></code></pre>
<p><strong>Note</strong>: Backbone passes the <code>attributes</code> object by shallow copy to the <code>validate</code> function using the Underscore <code>_.extend</code> method. This means that it is not possible to change any Number, String or Boolean attribute but it <em>is</em> possible to change attributes of objects because they are passed by reference. As shallow copy doesn't copy objects by implicitly copying them, but rather, by reference, one can change the attributes on those objects.</p>
<p>An example of this (by @fivetanley) is available <a href="http://jsfiddle.net/2NdDY/7/">here</a>.</p>
<h2 id="views-1"><a name="thebasics-views" id="thebasics-views">Views</a></h2>
<p>Views in Backbone don't contain the markup for your application, but rather they are there to support models by defining the logic for how they should be represented to the user. This is usually achieved using JavaScript templating (e.g. Mustache, jQuery-tmpl, etc.). A view's <code>render()</code> function can be bound to a model's <code>change()</code> event, allowing the view to always be up to date without requiring a full page refresh.</p>
<h4 id="creating-new-views">Creating new views</h4>
<p>Similar to the previous sections, creating a new view is relatively straight-forward. To create a new View, simply extend <code>Backbone.View</code>. I'll explain this code in detail below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoSearch = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
    <span class="dt">el</span>: $(<span class="ch">&#39;#results&#39;</span>),
    <span class="dt">render</span>: <span class="kw">function</span>( event ){
        <span class="kw">var</span> compiled_template = <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="st">&quot;#results-template&quot;</span>).<span class="fu">html</span>() );
        <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">html</span>( compiled_template(<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>()) );
        <span class="kw">return</span> <span class="kw">this</span>; <span class="co">//recommended as this enables calls to be chained.</span>
    },
    <span class="dt">events</span>: {
        <span class="st">&quot;submit #searchForm&quot;</span>: <span class="st">&quot;search&quot;</span>,
        <span class="st">&quot;click .reset&quot;</span>: <span class="st">&quot;reset&quot;</span>,
        <span class="st">&quot;click .advanced&quot;</span>: <span class="st">&quot;switchContext&quot;</span>
    },
    <span class="dt">search</span>: <span class="kw">function</span>( event ){
        <span class="co">//executed when a form &#39;#searchForm&#39; has been submitted</span>
    },
    <span class="dt">reset</span>: <span class="kw">function</span>( event ){
        <span class="co">//executed when an element with class &quot;reset&quot; has been clicked.</span>
    },
    <span class="dt">switchContext</span>: <span class="kw">function</span>( event ){
        <span class="co">//executed when an element with class &quot;advanced&quot; has been clicked.</span>
    }
});</code></pre>
<h4 id="what-is-el">What is <code>el</code>?</h4>
<p><code>el</code> is basically a reference to a DOM element and all views must have one. It allows for all of the contents of a view to be inserted into the DOM at once, which makes for faster rendering because the browser performs the minimum required reflows and repaints.</p>
<p>There are two ways to attach a DOM element to a view: the element already exists in the page or a new element is created for the view and added manually by the developer. If the element already exists in the page, you can set <code>el</code> as either a CSS selector that matches the element or a simple reference to the DOM element.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">el</span>: <span class="ch">&#39;#footer&#39;</span>,
<span class="co">// OR</span>
<span class="dt">el</span>: <span class="kw">document</span>.<span class="fu">getElementById</span>( <span class="ch">&#39;footer&#39;</span> )</code></pre>
<p>If you want to create a new element for your view, set any combination of the following view's properties: <code>tagName</code>, <code>id</code> and <code>className</code>. A new element will be created for you by the framework and a reference to it will be available at the <code>el</code> property.</p>
<pre><code>tagName: &#39;p&#39;, // required, but defaults to &#39;div&#39; if not set
className: &#39;container&#39;, // optional, you can assign multiple classes to this property like so &#39;container homepage&#39;
id: &#39;header&#39;, // optional</code></pre>
<p>The above code creates the <code>DOMElement</code> below but doesn't append it to the DOM.</p>
<pre><code>&lt;p id=&quot;header&quot; class=&quot;container&quot;&gt;&lt;/p&gt;</code></pre>
<p><strong>Understanding <code>render()</code></strong></p>
<p><code>render()</code> is an optional function that defines the logic for rendering a template. We'll use Underscore's micro-templating in these examples, but remember you can use other templating frameworks if you prefer.</p>
<p>The <code>_.template</code> method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the above view, I'm passing the markup from a template with id <code>results-template</code> to <code>_.template()</code> to be compiled. Next, I set the html of the <code>el</code> DOM element to the output of processing a JSON version of the model associated with the view through the compiled template.</p>
<p>Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code.</p>
<p><strong>The <code>events</code> attribute</strong></p>
<p>The Backbone <code>events</code> attribute allows us to attach event listeners to either custom selectors, or directly to <code>el</code> if no selector is provided. An event takes the form <code>{&quot;eventName selector&quot;: &quot;callbackFunction&quot;}</code> and a number of DOM event-types are supported, including <code>click</code>, <code>submit</code>, <code>mouseover</code>, <code>dblclick</code> and more.</p>
<p>What isn't instantly obvious is that under the bonnet, Backbone uses jQuery's <code>.delegate()</code> to provide instant support for event delegation but goes a little further, extending it so that <code>this</code> always refers to the current view object. The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corresponding function with the same name within the scope of your view.</p>
<h2 id="collections"><a name="thebasics-collections" id="thebasics-collections">Collections</a></h2>
<p>Collections are sets of Models and are created by extending <code>Backbone.Collection</code>.</p>
<p>Normally, when creating a collection you'll also want to pass through a property specifying the model that your collection will contain, as well as any instance properties required.</p>
<p>In the following example, we create a PhotoCollection that will contain our Photo models:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoCollection = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
    <span class="dt">model</span>: Photo
});</code></pre>
<p><strong>Getters and Setters</strong></p>
<p>There are a few different ways to retrieve a model from a collection. The most straight-forward is to use <code>Collection.get()</code> which accepts a single id as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> skiingEpicness = <span class="kw">PhotoCollection</span>.<span class="fu">get</span>(<span class="dv">2</span>);</code></pre>
<p>Sometimes you may also want to get a model based on its client id. The client id is a property that Backbone automatically assigns models that have not yet been saved. You can get a model's client id from its <code>.cid</code> property.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> mySkiingCrash = <span class="kw">PhotoCollection</span>.<span class="fu">getByCid</span>(<span class="dv">456</span>);</code></pre>
<p>Backbone Collections don't have setters as such, but do support adding new models via <code>.add()</code> and removing models via <code>.remove()</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> a = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Model</span>({ <span class="dt">title</span>: <span class="ch">&#39;my vacation&#39;</span>}),
    b = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Model</span>({ <span class="dt">title</span>: <span class="ch">&#39;my holiday&#39;</span>});

<span class="kw">var</span> photoCollection = <span class="kw">new</span> PhotoCollection([a,b]);
<span class="kw">photoCollection</span>.<span class="fu">remove</span>([a,b]);</code></pre>
<p><strong>Listening for events</strong></p>
<p>As collections represent a group of items, we're also able to listen for <code>add</code> and <code>remove</code> events for when new models are added or removed from the collection. Here's an example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();
<span class="kw">PhotoCollection</span>.<span class="fu">on</span>(<span class="st">&quot;add&quot;</span>, <span class="kw">function</span>(photo) {
  <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;I liked &quot;</span> + <span class="kw">photo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>) + <span class="ch">&#39; it\&#39;s this one, right? &#39;</span> + <span class="kw">photo</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>));
});

<span class="kw">PhotoCollection</span>.<span class="fu">add</span>([
  {<span class="dt">title</span>: <span class="st">&quot;My trip to Bali&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;bali-trip.jpg&quot;</span>},
  {<span class="dt">title</span>: <span class="st">&quot;The flight home&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;long-flight-oofta.jpg&quot;</span>},
  {<span class="dt">title</span>: <span class="st">&quot;Uploading pix&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;too-many-pics.jpg&quot;</span>}
]);</code></pre>
<p>In addition, we're able to bind a <code>change</code> event to listen for changes to models in the collection.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">PhotoCollection</span>.<span class="fu">on</span>(<span class="st">&quot;change:title&quot;</span>, <span class="kw">function</span>(){
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;there have been updates made to this collection&#39;s titles&quot;</span>);
});</code></pre>
<p><strong>Fetching models from the server</strong></p>
<p><code>Collections.fetch()</code> retrieves a default set of models from the server in the form of a JSON array. When this data returns, the current collection's contents will be replaced with the contents of the array.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>;
<span class="kw">PhotoCollection</span>.<span class="fu">url</span> = <span class="ch">&#39;/photos&#39;</span>;
<span class="kw">PhotoCollection</span>.<span class="fu">fetch</span>();</code></pre>
<p>During configuration, Backbone sets a variable to denote if extended HTTP methods are supported by the server. Another setting controls if the server understands the correct MIME type for JSON:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">emulateHTTP</span> = <span class="kw">false</span>;
<span class="kw">Backbone</span>.<span class="fu">emulateJSON</span> = <span class="kw">false</span>;</code></pre>
<p>The Backbone.sync method that uses these values is actually an integral part of Backbone.js. A jQuery-like ajax method is assumed, so HTTP parameters are organised based on jQuery’s API. Searching through the code for calls to the sync method show it’s used whenever a model is saved, fetched, or deleted (destroyed).</p>
<p>Under the covers, <code>Backbone.sync</code> is the function called every time Backbone tries to read or save models to the server. It uses jQuery or Zepto's ajax implementations to make these RESTful requests, however this can be overridden as per your needs. :</p>
<p>The sync function may be overriden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.</p>
<p>There’s no fancy plugin API for adding a persistence layer – simply override Backbone.sync with the same function signature:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model, options) {
};</code></pre>
<p>The default methodMap is useful for working out what the method argument does:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> methodMap = {
  <span class="ch">&#39;create&#39;</span>: <span class="ch">&#39;POST&#39;</span>,
  <span class="ch">&#39;update&#39;</span>: <span class="ch">&#39;PUT&#39;</span>,
  <span class="ch">&#39;delete&#39;</span>: <span class="ch">&#39;DELETE&#39;</span>,
  <span class="ch">&#39;read&#39;</span>: <span class="ch">&#39;GET&#39;</span>
};</code></pre>
<p>In the above example if we wanted to log an event when <code>.sync()</code> was called, we could do this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> id_counter = <span class="dv">1</span>;
<span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model) {
  <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;I&#39;ve been passed &quot;</span> + method + <span class="st">&quot; with &quot;</span> + <span class="kw">JSON</span>.<span class="fu">stringify</span>(model));
  <span class="kw">if</span>(method === <span class="ch">&#39;create&#39;</span>){ <span class="kw">model</span>.<span class="fu">set</span>(<span class="ch">&#39;id&#39;</span>, id_counter++); }
};</code></pre>
<p><strong>Resetting/Refreshing Collections</strong></p>
<p>Rather than adding or removing models individually, you might occasionally wish to update an entire collection at once. <code>Collection.reset()</code> allows us to replace an entire collection with new models as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">PhotoCollection</span>.<span class="fu">reset</span>([
  {<span class="dt">title</span>: <span class="st">&quot;My trip to Scotland&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;scotland-trip.jpg&quot;</span>},
  {<span class="dt">title</span>: <span class="st">&quot;The flight from Scotland&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;long-flight.jpg&quot;</span>},
  {<span class="dt">title</span>: <span class="st">&quot;Latest snap of Loch Ness&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;lochness.jpg&quot;</span>}]);</code></pre>
<p>Note that using <code>Collection.reset()</code> doesn't fire any <code>add</code> or <code>remove</code> events. A <code>reset</code> event is fired instead.</p>
<h3 id="underscore-utility-functions">Underscore utility functions</h3>
<p>As Backbone requires Underscore as a hard dependency, we're able to use many of the utilities it has to offer to aid with our application development. Here's an example of how Underscore's <code>sortBy()</code> method can be used to sort a collection of photos based on a particular attribute.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> sortedByAlphabet = <span class="kw">PhotoCollection</span>.<span class="fu">sortBy</span>(<span class="kw">function</span> (photo) {
    <span class="kw">return</span> <span class="kw">photo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>).<span class="fu">toLowerCase</span>();
});</code></pre>
<p>The complete list of what Underscore can do is beyond the scope of this guide, but can be found in its official <a href="http://documentcloud.github.com/underscore/">docs</a>.</p>
<h3 id="chainable-api">Chainable API</h3>
<p>Speaking of utility methods, another bit of sugar in Backbone is the support for Underscore’s chain method. This works by calling the original method with the current array of models and returning the result. In case you haven’t seen it before, the chainable API looks like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> collection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>([
  { <span class="dt">name</span>: <span class="ch">&#39;Tim&#39;</span>, <span class="dt">age</span>: <span class="dv">5</span> },
  { <span class="dt">name</span>: <span class="ch">&#39;Ida&#39;</span>, <span class="dt">age</span>: <span class="dv">26</span> },
  { <span class="dt">name</span>: <span class="ch">&#39;Rob&#39;</span>, <span class="dt">age</span>: <span class="dv">55</span> }
]);

<span class="kw">collection</span>.<span class="fu">chain</span>()
  .<span class="fu">filter</span>(<span class="kw">function</span>(item) { <span class="kw">return</span> <span class="kw">item</span>.<span class="fu">get</span>(<span class="ch">&#39;age&#39;</span>) &gt; <span class="dv">10</span>; })
  .<span class="fu">map</span>(<span class="kw">function</span>(item) { <span class="kw">return</span> <span class="kw">item</span>.<span class="fu">get</span>(<span class="ch">&#39;name&#39;</span>); })
  .<span class="fu">value</span>();

<span class="co">// Will return [&#39;Ida&#39;, &#39;Rob&#39;]</span></code></pre>
<p>Some of the Backbone-specific method will return <code>this</code>, which means they can be chained as well:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> collection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();

collection
    .<span class="fu">add</span>({ <span class="dt">name</span>: <span class="ch">&#39;John&#39;</span>, <span class="dt">age</span>: <span class="dv">23</span> })
    .<span class="fu">add</span>({ <span class="dt">name</span>: <span class="ch">&#39;Harry&#39;</span>, <span class="dt">age</span>: <span class="dv">33</span> })
    .<span class="fu">add</span>({ <span class="dt">name</span>: <span class="ch">&#39;Steve&#39;</span>, <span class="dt">age</span>: <span class="dv">41</span> });

<span class="kw">collection</span>.<span class="fu">pluck</span>(<span class="ch">&#39;name&#39;</span>);
<span class="co">// [&#39;John&#39;, &#39;Harry&#39;, &#39;Steve&#39;]</span></code></pre>
<h2 id="events"><a name="thebasics-events" id="thebasics-events">Events</a></h2>
<p>As we've covered, Backbone's objects are designed to be inherited from and every single one of the following objects inherits from <code>Backbone.Events</code>:</p>
<ul>
<li>Backbone.Model</li>
<li>Backbone.Collection</li>
<li>Backbone.Router</li>
<li>Backbone.History</li>
<li>Backbone.View</li>
</ul>
<p>Events are the standard way to deal with user interface actions, through the declarative event bindings on views, and also model and collection changes. Mastering events is one of the quickest ways to become more productive with Backbone.</p>
<p><code>Backbone.Events</code> also has the ability to give any object a way to bind and trigger custom events. We can mix this module into any object easily and there isn't a requirement for events to be declared prior to them being bound.</p>
<p>Example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};

<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);

<span class="co">// Add a custom event</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance&quot;</span>, <span class="kw">function</span>(msg){
  <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We triggered &quot;</span> + msg);
});

<span class="co">// Trigger the custom event</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>, <span class="st">&quot;our event&quot;</span>);</code></pre>
<p>If you're familiar with jQuery custom events or the concept of Publish/Subscribe, <code>Backbone.Events</code> provides a system that is very similar with <code>on</code> being analogous to <code>subscribe</code> and <code>trigger</code> being similar to <code>publish</code>.</p>
<p><code>on</code> basically allows us to bind a callback function to any object, as we've done with <code>dance</code> in the above example. Whenever the event is fired, our callback is invoked.</p>
<p>The official Backbone.js documentation recommends namespacing event names using colons if you end up using quite a few of these on your page. e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance:tap&quot;</span>, ...);</code></pre>
<p>A special <code>all</code> event is made available in case you would like an event to be triggered when any event occurs (e.g if you would like to screen events in a single location). The <code>all</code> event can be used as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;all&quot;</span>, <span class="kw">function</span>(eventName){
  <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;The name of the event passed was &quot;</span> + eventName);
});</code></pre>
<p><code>off</code> allows us to remove a callback function that has previously been bound from an object. Going back to our Publish/Subscribe comparison, think of it as an <code>unsubscribe</code> for custom events.</p>
<p>To remove the <code>dance</code> event we previously bound to <code>myObject</code>, we would simply do:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">myObject</span>.<span class="fu">off</span>(<span class="st">&quot;dance&quot;</span>);</code></pre>
<p>This will remove all callbacks for the <code>dance</code> event. If we wish to remove just a callback by a specific name, we can do:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">myObject</span>.<span class="fu">off</span>(<span class="st">&quot;dance&quot;</span>, callbackName);</code></pre>
<p>Finally, <code>trigger</code> triggers a callback for a specified event (or a space-separated listof events). e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Single event</span>
<span class="kw">myObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>);

<span class="co">// Multiple events</span>
<span class="kw">myObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance jump skip&quot;</span>);</code></pre>
<p>It is also possible to pass along additional arguments to each (or all) of these events via a second argument supported by <code>trigger</code>. e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">myObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>, {<span class="dt">duration</span>: <span class="st">&quot;5 minutes&quot;</span>});</code></pre>
<h2 id="routers"><a name="thebasics-routers" id="thebasics-routers">Routers</a></h2>
<p>In Backbone, routers are used to help manage application state and for connecting URLs to application events. This is achieved using hash-tags with URL fragments, or using the browser's pushState and History API. Some examples of routes may be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">http</span>:<span class="co">//unicorns.com/#whatsup</span>
<span class="dt">http</span>:<span class="co">//unicorns.com/#search/seasonal-horns/page2</span></code></pre>
<p>Note: An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that particular route. This relationship is defined as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="st">&quot;route&quot;</span> : <span class="st">&quot;mappedFunction&quot;</span></code></pre>
<p>Let us now define our first controller by extending <code>Backbone.Router</code>. For the purposes of this guide, we're going to continue pretending we're creating a photo gallery application that requires a GalleryRouter.</p>
<p>Note the inline comments in the code example below as they continue the rest of the lesson on routers.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> GalleryRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
    <span class="co">/* define the route and function maps for this router */</span>
    <span class="dt">routes</span>: {
        <span class="st">&quot;about&quot;</span> : <span class="st">&quot;showAbout&quot;</span>,
        <span class="co">/*Sample usage: http://unicorns.com/#about*/</span>

        <span class="st">&quot;photos/:id&quot;</span> : <span class="st">&quot;getPhoto&quot;</span>,
        <span class="co">/*This is an example of using a &quot;:param&quot; variable which allows us to match</span>
<span class="co"> any of the components between two URL slashes*/</span>
        <span class="co">/*Sample usage: http://unicorns.com/#photos/5*/</span>

        <span class="st">&quot;search/:query&quot;</span> : <span class="st">&quot;searchPhotos&quot;</span>,
        <span class="co">/*We can also define multiple routes that are bound to the same map function,</span>
<span class="co"> in this case searchPhotos(). Note below how we&#39;re optionally passing in a</span>
<span class="co"> reference to a page number if one is supplied*/</span>
        <span class="co">/*Sample usage: http://unicorns.com/#search/lolcats*/</span>

        <span class="st">&quot;search/:query/p:page&quot;</span> : <span class="st">&quot;searchPhotos&quot;</span>,
        <span class="co">/*As we can see, URLs may contain as many &quot;:param&quot;s as we wish*/</span>
        <span class="co">/*Sample usage: http://unicorns.com/#search/lolcats/p1*/</span>

        <span class="st">&quot;photos/:id/download/*imagePath&quot;</span> : <span class="st">&quot;downloadPhoto&quot;</span>,
        <span class="co">/*This is an example of using a *splat. splats are able to match any number of</span>
<span class="co"> URL components and can be combined with &quot;:param&quot;s*/</span>
        <span class="co">/*Sample usage: http://unicorns.com/#photos/5/download/files/lolcat-car.jpg*/</span>

        <span class="co">/*If you wish to use splats for anything beyond default routing, it&#39;s probably a good</span>
<span class="co"> idea to leave them at the end of a URL otherwise you may need to apply regular</span>
<span class="co"> expression parsing on your fragment*/</span>

        <span class="st">&quot;*other&quot;</span> : <span class="st">&quot;defaultRoute&quot;</span>
        <span class="co">/*This is a default route that also uses a *splat. Consider the</span>
<span class="co"> default route a wildcard for URLs that are either not matched or where</span>
<span class="co"> the user has incorrectly typed in a route path manually*/</span>
        <span class="co">/*Sample usage: http://unicorns.com/#anything*/</span>

    },

    <span class="dt">showAbout</span>: <span class="kw">function</span>(){
    },

    <span class="dt">getPhoto</span>: <span class="kw">function</span>(id){
        <span class="co">/*</span>
<span class="co"> Note that the id matched in the above route will be passed to this function</span>
<span class="co"> */</span>
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;You are trying to reach photo &quot;</span> + id);
    },

    <span class="dt">searchPhotos</span>: <span class="kw">function</span>(query, page){
        <span class="kw">var</span> page_number = page || <span class="dv">1</span>;
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Page number: &quot;</span> + page_number + <span class="st">&quot; of the results for &quot;</span> + query);
    },

    <span class="dt">downloadPhoto</span>: <span class="kw">function</span>(id, path){
    },

    <span class="dt">defaultRoute</span>: <span class="kw">function</span>(other){
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Invalid. You attempted to reach:&quot;</span> + other);
    }
});

<span class="co">/* Now that we have a router setup, remember to instantiate it*/</span>

<span class="kw">var</span> myGalleryRouter = <span class="kw">new</span> GalleryRouter();</code></pre>
<p>As of Backbone 0.5+, it's possible to opt-in for HTML5 pushState support via <code>window.history.pushState</code>. This permits you to define routes such as http://www.scriptjunkie.com/just/an/example. This will be supported with automatic degradation when a user's browser doesn't support pushState. For the purposes of this tutorial, we'll use the hashtag method.</p>
<h4 id="is-there-a-limit-to-the-number-of-routers-i-should-be-using">Is there a limit to the number of routers I should be using?</h4>
<p>Andrew de Andrade has pointed out that DocumentCloud themselves usually only use a single router in most of their applications. You're very likely to not require more than one or two routers in your own projects as the majority of your application routing can be kept organized in a single controller without it getting unwieldy.</p>
<h4 id="backbone.history">Backbone.history</h4>
<p>Next, we need to initialize <code>Backbone.history</code> as it handles <code>hashchange</code> events in our application. This will automatically handle routes that have been defined and trigger callbacks when they've been accessed.</p>
<p>The <code>Backbone.history.start()</code> method will simply tell Backbone that it's OK to begin monitoring all <code>hashchange</code> events as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone.history</span>.<span class="fu">start</span>();
<span class="kw">Router</span>.<span class="fu">navigate</span>();</code></pre>
<p>As an aside, if you would like to save application state to the URL at a particular point you can use the <code>.navigate()</code> method to achieve this. It simply updates your URL fragment without the need to trigger the <code>hashchange</code> event:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/*Lets imagine we would like a specific fragment for when a user zooms into a photo*/</span>
<span class="dt">zoomPhoto</span>: <span class="kw">function</span>(factor){
    <span class="kw">this</span>.<span class="fu">zoom</span>(factor); <span class="co">//imagine this zooms into the image</span>
    <span class="kw">this</span>.<span class="fu">navigate</span>(<span class="st">&quot;zoom/&quot;</span> + factor); <span class="co">//updates the fragment for us, but doesn&#39;t trigger the route</span>
}</code></pre>
<p>It is also possible for <code>Router.navigate()</code> to trigger the route as well as updating the URL fragment.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">zoomPhoto</span>: <span class="kw">function</span>(factor){
    <span class="kw">this</span>.<span class="fu">zoom</span>(factor); <span class="co">//imagine this zooms into the image</span>
    <span class="kw">this</span>.<span class="fu">navigate</span>(<span class="st">&quot;zoom/&quot;</span> + factor, <span class="kw">true</span>); <span class="co">//updates the fragment for us and triggers the route</span>
}</code></pre>
<h3 id="backbones-sync-api">Backbone’s Sync API</h3>
<p>The Backbone.sync method is intended to be overridden to support other backends. The built-in method is tailed to a certain breed of RESTful JSON APIs – Backbone was originally extracted from a Ruby on Rails application, which uses HTTP methods like PUT the same way.</p>
<p>The way this works is the model and collection classes have a sync method that calls Backbone.sync. Both will call this.sync internally when fetching, saving, or deleting items.</p>
<p>The sync method is called with three parameters:</p>
<ul>
<li>method: One of create, update, delete, read</li>
<li>model: The Backbone model object</li>
<li>options: May include success and error methods</li>
</ul>
<p>Implementing a new sync method can use the following pattern:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model, options) {
  <span class="kw">var</span> requestContent = {}, success, error;

  <span class="kw">function</span> success(result) {
    <span class="co">// Handle results from MyAPI</span>
    <span class="kw">if</span> (<span class="kw">options</span>.<span class="fu">success</span>) {
      <span class="kw">options</span>.<span class="fu">success</span>(result);
    }
  }

  <span class="kw">function</span> error(result) {
    <span class="co">// Handle results from MyAPI</span>
    <span class="kw">if</span> (<span class="kw">options</span>.<span class="fu">error</span>) {
      <span class="kw">options</span>.<span class="fu">error</span>(result);
    }
  }

  options || (options = {});

  <span class="kw">switch</span> (method) {
    <span class="kw">case</span> <span class="ch">&#39;create&#39;</span>:
      requestContent[<span class="ch">&#39;resource&#39;</span>] = <span class="kw">model</span>.<span class="fu">toJSON</span>();
      <span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">create</span>(model, success, error);

    <span class="kw">case</span> <span class="ch">&#39;update&#39;</span>:
      requestContent[<span class="ch">&#39;resource&#39;</span>] = <span class="kw">model</span>.<span class="fu">toJSON</span>();
      <span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">update</span>(model, success, error);

    <span class="kw">case</span> <span class="ch">&#39;delete&#39;</span>:
      <span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">destroy</span>(model, success, error);

    <span class="kw">case</span> <span class="ch">&#39;read&#39;</span>:
      <span class="kw">if</span> (<span class="kw">model</span>.<span class="fu">attributes</span>[<span class="kw">model</span>.<span class="fu">idAttribute</span>]) {
        <span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">find</span>(model, success, error);
      } <span class="kw">else</span> {
        <span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">findAll</span>(model, success, error);
      }
  }
};</code></pre>
<p>This pattern delegates API calls to a new object, which could be a Backbone-style class that supports events. This can be safely tested separately, and potentially used with libraries other than Backbone.</p>
<p>There are quite a few sync implementations out there:</p>
<ul>
<li>Backbone localStorage</li>
<li>Backbone offline</li>
<li>Backbone Redis</li>
<li>backbone-parse</li>
<li>backbone-websql</li>
<li>Backbone Caching Sync</li>
</ul>
<h3 id="conflict-management">Conflict Management</h3>
<p>Like most client-side projects, Backbone.js wraps everything in an immediately-invoked function expression:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">(<span class="kw">function</span>(){
  <span class="co">// Backbone.js</span>
}).<span class="fu">call</span>(<span class="kw">this</span>);</code></pre>
<p>Several things happen during this configuration stage. A Backbone “namespace” is created, and multiple versions of Backbone on the same page are supported through the noConflict mode:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> root = <span class="kw">this</span>;
<span class="kw">var</span> previousBackbone = <span class="kw">root</span>.<span class="fu">Backbone</span>;

<span class="kw">Backbone</span>.<span class="fu">noConflict</span> = <span class="kw">function</span>() {
  <span class="kw">root</span>.<span class="fu">Backbone</span> = previousBackbone;
  <span class="kw">return</span> <span class="kw">this</span>;
};</code></pre>
<p>Multiple versions of Backbone can be used on the same page by calling noConflict like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Backbone19 = <span class="kw">Backbone</span>.<span class="fu">noConflict</span>();
<span class="co">// Backbone19 refers to the most recently loaded version,</span>
<span class="co">// and `window.Backbone` will be restored to the previously</span>
<span class="co">// loaded version</span></code></pre>
<p>This initial configuration code also supports CommonJS modules so Backbone can be used in Node projects:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Backbone;
<span class="kw">if</span> (<span class="kw">typeof</span> exports !== <span class="ch">&#39;undefined&#39;</span>) {
  Backbone = exports;
} <span class="kw">else</span> {
  Backbone = <span class="kw">root</span>.<span class="fu">Backbone</span> = {};
}</code></pre>
<h2 id="inheritance-mixins"><a name="thebasics-inheritance" id="thebasics-inheritance">Inheritance &amp; Mixins</a></h2>
<p>For its inheritance, Backbone internally uses an <code>inherits</code> function inspired by <code>goog.inherits</code>, Google’s implementation from the Closure Library. It's basically a function to correctly setup the prototype chain.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="kw">var</span> inherits = <span class="kw">function</span>(parent, protoProps, staticProps) {
      ...</code></pre>
<p>The only major difference here is that Backbone’s API accepts two objects containing “instance” and “static” methods.</p>
<p>Following on from this, for inheritance purposes all of Backbone's objects contain an <code>extend</code> method as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Model</span>.<span class="fu">extend</span> = <span class="kw">Collection</span>.<span class="fu">extend</span> = <span class="kw">Router</span>.<span class="fu">extend</span> = <span class="kw">View</span>.<span class="fu">extend</span> = extend;</code></pre>
<p>Most development with Backbone is based around inheriting from these objects, and they’re designed to mimic a classical object-oriented implementation.</p>
<p>If this sounds familiar, it's because <code>extend</code> is an Underscore.js utility, although Backbone itself does a lot more with this. See below for Underscore's <code>extend</code>:</p>
<pre><code>each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
    obj[prop] = source[prop];
  }
});
return obj;</code></pre>
<p>The above isn’t quite the same as ES5’s <code>Object.create</code>, as it’s actually copying properties (methods and values) from one object to another. As this isn’t enough to support Backbone’s inheritance and class model, the following steps are performed:</p>
<ul>
<li>The instance methods are checked to see if there’s a constructor property. If so, the class’s constructor is used, otherwise the parent’s constructor is used (i.e., Backbone.Model)</li>
<li>Underscore’s extend method is called to add the parent class’s methods to the new child class</li>
<li>The <code>prototype</code> property of a blank constructor function is assigned with the parent’s prototype, and a new instance of this is set to the child’s <code>prototype</code> property Underscore’s extend method is called twice to add the static and instance methods to the child class</li>
<li>The child’s prototype’s constructor and a <code>__super__</code> property are assigned</li>
<li>This pattern is also used for classes in CoffeeScript, so Backbone classes are compatible with CoffeeScript classes.</li>
</ul>
<p><code>extend</code> can be used for a great deal more and developers who are fans of mixins will like that it can be used for this too. You can define functionality on any custom object, and then quite literally copy &amp; paste all of the methods and attributes from that object to a Backbone one:</p>
<p>For example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="kw">var</span> MyMixin = {
  <span class="dt">foo</span>: <span class="st">&quot;bar&quot;</span>,
  <span class="dt">sayFoo</span>: <span class="kw">function</span>(){alert(<span class="kw">this</span>.<span class="fu">foo</span>);}
}

<span class="kw">var</span> MyView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
 <span class="co">// ...</span>
});

<span class="kw">_</span>.<span class="fu">extend</span>(<span class="kw">MyView</span>.<span class="fu">prototype</span>, MyMixin);

myView = <span class="kw">new</span> MyView();
<span class="kw">myView</span>.<span class="fu">sayFoo</span>(); <span class="co">//=&gt; &quot;bar&quot;</span></code></pre>
<p>We can take this further and also apply it to View inheritance. The following is an example of how to extend one View using another:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Panel = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
});

<span class="kw">var</span> PanelAdvanced = <span class="kw">Panel</span>.<span class="fu">extend</span>({
});</code></pre>
<p>However, if you have an <code>initialize()</code> method in Panel, then it won't be called if you also have an <code>initialize()</code> method in PanelAdvanced, so you would have to call Panel's initialize method explicitly:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Panel = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
   <span class="dt">initialize</span>: <span class="kw">function</span>(options){
      <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Panel initialized&#39;</span>);
      <span class="kw">this</span>.<span class="fu">foo</span> = <span class="ch">&#39;bar&#39;</span>;
   }
});

<span class="kw">var</span> PanelAdvanced = <span class="kw">Panel</span>.<span class="fu">extend</span>({
   <span class="dt">initialize</span>: <span class="kw">function</span>(options){
      <span class="kw">this</span>.<span class="fu">constructor</span>.__<span class="fu">super</span>__.<span class="fu">initialize</span>.<span class="fu">apply</span>(<span class="kw">this</span>, [options])
      <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;PanelAdvanced initialized&#39;</span>);
      <span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">this</span>.<span class="fu">foo</span>); <span class="co">// Log: bar</span>
   }
});</code></pre>
<p>This isn't the most elegant of solutions because if you have a lot of Views that inherit from Panel, then you'll have to remember to call Panel's initialize from all of them.</p>
<p>It's worth noting that if Panel doesn't have an initialize method now but you choose to add it in the future, then you'll need to go to all of the inherited classes in the future and make sure they call Panel's initialize.</p>
<p>So here's an alternative way to define Panel so that your inherited views don't need to call Panel's initialize method:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Panel = <span class="kw">function</span> (options) {

    <span class="co">// put all of Panel&#39;s initialization code here</span>
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Panel initialized&#39;</span>);
    <span class="kw">this</span>.<span class="fu">foo</span> = <span class="ch">&#39;bar&#39;</span>;

    <span class="kw">Backbone.View</span>.<span class="fu">apply</span>(<span class="kw">this</span>, [options]);
};

<span class="kw">_</span>.<span class="fu">extend</span>(<span class="kw">Panel</span>.<span class="fu">prototype</span>, <span class="kw">Backbone.View</span>.<span class="fu">prototype</span>, {

    <span class="co">// put all of Panel&#39;s methods here. For example:</span>
    <span class="dt">sayHi</span>: <span class="kw">function</span> () {
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;hello from Panel&#39;</span>);
    }
});

<span class="kw">Panel</span>.<span class="fu">extend</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>;


<span class="co">// other classes then inherit from Panel like this:</span>
<span class="kw">var</span> PanelAdvanced = <span class="kw">Panel</span>.<span class="fu">extend</span>({

    <span class="dt">initialize</span>: <span class="kw">function</span> (options) {
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;PanelAdvanced initialized&#39;</span>);
        <span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">this</span>.<span class="fu">foo</span>);
    }
});

<span class="kw">var</span> PanelAdvanced = <span class="kw">new</span> PanelAdvanced(); <span class="co">//Log: Panel initialized, PanelAdvanced initialized, bar</span>
<span class="kw">PanelAdvanced</span>.<span class="fu">sayHi</span>(); <span class="co">// Log: hello from Panel</span></code></pre>
<p>When used appropriately, Backbone's <code>extend</code> method can save a great deal of time and effort writing redundant code.</p>
<p>(Thanks to <a href="http://dailyjs.com">Alex Young</a>, <a href="http://stackoverflow.com/users/93448/derick-bailey">Derick Bailey</a> and <a href="http://stackoverflow.com/users/188740/johnnyo">JohnnyO</a> for the heads up about these tips).</p>
<h2 id="namespacing"><a name="thebasics-namespacing" id="thebasics-namespacing">Namespacing</a></h2>
<p>When learning how to use Backbone, an important and commonly overlooked area by tutorials is namespacing. If you already have experience with namespacing in JavaScript, the following section will provide some advice on how to specifically apply concepts you know to Backbone, however I will also be covering explanations for beginners to ensure everyone is on the same page.</p>
<h4 id="what-is-namespacing">What is namespacing?</h4>
<p>The basic idea around namespacing is to avoid collisions with other objects or variables in the global namespace. They're important as it's best to safeguard your code from breaking in the event of another script on the page using the same variable names as you are. As a good 'citizen' of the global namespace, it's also imperative that you do your best to similarly not prevent other developer's scripts executing due to the same issues.</p>
<p>JavaScript doesn't really have built-in support for namespaces like other languages, however it does have closures which can be used to achieve a similar effect.</p>
<p>In this section we'll be taking a look shortly at some examples of how you can namespace your models, views, routers and other components specifically. The patterns we'll be examining are:</p>
<ul>
<li>Single global variables</li>
<li>Object Literals</li>
<li>Nested namespacing</li>
</ul>
<p><strong>Single global variables</strong></p>
<p>One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myApplication = (<span class="kw">function</span>(){
    <span class="kw">function</span>(){
      <span class="co">// ...</span>
    },
    <span class="kw">return</span> {
      <span class="co">// ...</span>
    }
})();</code></pre>
<p>You've probably seen this technique before. A Backbone-specific example might look like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myViews = (<span class="kw">function</span>(){
    <span class="kw">return</span> {
        <span class="dt">PhotoView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. }),
        <span class="dt">GalleryView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. }),
        <span class="dt">AboutView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. });
        <span class="co">//etc.</span>
    };
})();</code></pre>
<p>Here we can return a set of views, but the same technique could return an entire collection of models, views and routers depending on how you decide to structure your application. Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page.</p>
<p>One solution to this problem, as mentioned by Peter Michaux, is to use prefix namespacing. It's a simple concept at heart, but the idea is you select a common prefix name (in this example, <code>myApplication_</code>) and then define any methods, variables or other objects after the prefix.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myApplication_photoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({}),
myApplication_galleryView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});</code></pre>
<p>This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow.</p>
<p>For more on Peter's views about the single global variable pattern, read his <a href="http://michaux.ca/articles/javascript-namespacing">excellent post on them</a>.</p>
<p>Note: There are several other variations on the single global variable pattern out in the wild, however having reviewed quite a few, I felt the prefixing approach applied best to Backbone.</p>
<p><strong>Object Literals</strong></p>
<p>Object Literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They're beneficial if you wish to create easily readable structures that can be expanded to support deep nesting. Unlike simple global variables, Object Literals often also take into account tests for the existence of a variable by the same name, which helps reduce the chances of collision.</p>
<p>This example demonstrates two ways you can check to see if a namespace already exists before defining it. I commonly use Option 2.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/*Doesn&#39;t check for existence of myApplication*/</span>
<span class="kw">var</span> myApplication = {};

<span class="co">/*</span>
<span class="co">Does check for existence. If already defined, we use that instance.</span>
<span class="co">Option 1: if(!myApplication) myApplication = {};</span>
<span class="co">Option 2: var myApplication = myApplication || {};</span>
<span class="co">We can then populate our object literal to support models, views and collections (or any data, really):</span>
<span class="co">*/</span>

<span class="kw">var</span> myApplication = {
    <span class="dt">models </span>: {},
    <span class="dt">views </span>: {
        <span class="dt">pages </span>: {}
    },
    <span class="dt">collections </span>: {}
};</code></pre>
<p>One can also opt for adding properties directly to the namespace (such as your views, in the following example):</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myGalleryViews = myGalleryViews || {};
<span class="kw">myGalleryViews</span>.<span class="fu">photoView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});
<span class="kw">myGalleryViews</span>.<span class="fu">galleryView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});</code></pre>
<p>The benefit of this pattern is that you're able to easily encapsulate all of your models, views, routers etc. in a way that clearly separates them and provides a solid foundation for extending your code.</p>
<p>This pattern has a number of benefits. It's often a good idea to decouple the default configuration for your application into a single area that can be easily modified without the need to search through your entire codebase just to alter it. Here's an example of a hypothetical object literal that stores application configuration settings:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myConfig = {
    <span class="dt">language</span>: <span class="ch">&#39;english&#39;</span>,
    <span class="dt">defaults</span>: {
        <span class="dt">enableGeolocation</span>: <span class="kw">true</span>,
        <span class="dt">enableSharing</span>: <span class="kw">false</span>,
        <span class="dt">maxPhotos</span>: <span class="dv">20</span>
    },
    <span class="dt">theme</span>: {
        <span class="dt">skin</span>: <span class="ch">&#39;a&#39;</span>,
        <span class="dt">toolbars</span>: {
            <span class="dt">index</span>: <span class="ch">&#39;ui-navigation-toolbar&#39;</span>,
            <span class="dt">pages</span>: <span class="ch">&#39;ui-custom-toolbar&#39;</span>
        }
    }
}</code></pre>
<p>Note that there are really only minor syntactical differences between the Object Literal pattern and a standard JSON data set. If for any reason you wish to use JSON for storing your configurations instead (e.g. for simpler storage when sending to the back-end), feel free to.</p>
<p>For more on the Object Literal pattern, I recommend reading Rebecca Murphey's <a href="http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code">excellent article on the topic</a>.</p>
<p><strong>Nested namespacing</strong></p>
<p>An extension of the Object Literal pattern is nested namespacing. It's another common pattern used that offers a lower risk of collision due to the fact that even if a top-level namespace already exists, it's unlikely the same nested children do. For example, Yahoo's YUI uses the nested object namespacing pattern extensively:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">YAHOO.util.Dom</span>.<span class="fu">getElementsByClassName</span>(<span class="ch">&#39;test&#39;</span>);</code></pre>
<p>Yahoo's YUI uses the nested object namespacing pattern regularly and even DocumentCloud (the creators of Backbone) use the nested namespacing pattern in their main applications. A sample implementation of nested namespacing with Backbone may look like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> galleryApp = galleryApp || {};

<span class="co">// perform similar check for nested children</span>
<span class="kw">galleryApp</span>.<span class="fu">routers</span> = <span class="kw">galleryApp</span>.<span class="fu">routers</span> || {};
<span class="kw">galleryApp</span>.<span class="fu">model</span> = <span class="kw">galleryApp</span>.<span class="fu">model</span> || {};
<span class="kw">galleryApp.model</span>.<span class="fu">special</span> = <span class="kw">galleryApp.model</span>.<span class="fu">special</span> || {};

<span class="co">// routers</span>
<span class="kw">galleryApp.routers</span>.<span class="fu">Workspace</span> = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({});
<span class="kw">galleryApp.routers</span>.<span class="fu">PhotoSearch</span> = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({});

<span class="co">// models</span>
<span class="kw">galleryApp.model</span>.<span class="fu">Photo</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});
<span class="kw">galleryApp.model</span>.<span class="fu">Comment</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});

<span class="co">// special models</span>
<span class="kw">galleryApp.model.special</span>.<span class="fu">Admin</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});</code></pre>
<p>This is readable, clearly organized, and is a relatively safe way of namespacing your Backbone application. The only real caveat however is that it requires your browser's JavaScript engine to first locate the galleryApp object, then dig down until it gets to the function you're calling. However, developers such as Juriy Zaytsev (kangax) have tested and found the performance differences between single object namespacing vs the 'nested' approach to be quite negligible.</p>
<p><strong>Recommendation</strong></p>
<p>Reviewing the namespace patterns above, the option that I prefer when writing Backbone applications is nested object namespacing with the object literal pattern.</p>
<p>Single global variables may work fine for applications that are relatively trivial. However, larger codebases requiring both namespaces and deep sub-namespaces require a succinct solution that's both readable and scalable. I feel this pattern achieves both of these objectives and is a good choice for most Backbone development.</p>
<h1 id="practical-todos---your-first-backbone.js-app"><a name="practicaltodos">Practical: Todos - Your First Backbone.js App</a></h1>
<p>Now that we've journeyed through the fundamentals, let's move on to writing our first Backbone.js app - a Todo List application. Building a Todo List is a great way to learn about Backbone’s conventions. It's a simple enough app, but contains enough interesting problems to be useful, such as binding, persisting model data, routing and template rendering.</p>
<p>For this chapter, we’re going to learn how to create the Backbone.js Todo app listed on <a href="http://todomvc.com">TodoMVC.com</a>.</p>
<img src="img/todoapp.png" width="700px"/>
<p>Let's think about what we need from a high level architectural standpoint.</p>
<ul>
<li>A <code>Todo</code> model to describe individual todo items</li>
<li>A <code>TodoList</code> collection to store and persist todos</li>
<li>A way of creating todos</li>
<li>Listing todos</li>
<li>Editing existing todos</li>
<li>Completing todos</li>
<li>Deleting todos</li>
<li>A way to bookmark the items that have been completed or are remaining</li>
</ul>
<p>Basically your classic <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> methods. Let's get started!</p>
<h2 id="index">Index</h2>
<p>The first step is to setup the basic application dependencies, which in this case will be: <a href="http://jquery.com">jQuery</a>, <a href="http://underscorejs.org">Underscore</a>, Backbone.js and the <a href="https://github.com/jeromegn/Backbone.localStorage">Backbone LocalStorage adapter</a>. These will be loaded in our main (and only) HTML file, index.html:</p>
<pre><code>
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge,chrome=1&quot;&gt;
  &lt;title&gt;Backbone.js • TodoMVC&lt;/title&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;../../assets/base.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;script src=&quot;../../assets/base.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;../../assets/jquery.min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/lib/underscore-min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/lib/backbone-min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/lib/backbone-localstorage.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/models/todo.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/collections/todos.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/views/todos.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/views/app.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/routers/router.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;js/app.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>To help demonstrate how the various parts of our application can be split up, individual concerns are cleanly organized into folders representing our models, views, collections and routers. An app.js file is used to kick everything off.</p>
<h2 id="application-html">Application HTML</h2>
<p>Now let's take a look at our application's static HTML. We're going to need an <code>&lt;input&gt;</code> for creating new todos, a <code>&lt;ul id=&quot;todo-list&quot; /&gt;</code> for listing the actual todos, and a section containing some operations, such as clearing completed todos.</p>
<pre><code> &lt;section id=&quot;todoapp&quot;&gt;
    &lt;header id=&quot;header&quot;&gt;
      &lt;h1&gt;todos&lt;/h1&gt;
      &lt;input id=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; autofocus&gt;
    &lt;/header&gt;
    &lt;section id=&quot;main&quot;&gt;
      &lt;input id=&quot;toggle-all&quot; type=&quot;checkbox&quot;&gt;
      &lt;label for=&quot;toggle-all&quot;&gt;Mark all as complete&lt;/label&gt;
      &lt;ul id=&quot;todo-list&quot;&gt;&lt;/ul&gt;
    &lt;/section&gt;
    &lt;footer id=&quot;footer&quot;&gt;&lt;/footer&gt;
  &lt;/section&gt;
  &lt;div id=&quot;info&quot;&gt;
    &lt;p&gt;Double-click to edit a todo&lt;/p&gt;
    &lt;p&gt;Written by &lt;a href=&quot;https://github.com/addyosmani&quot;&gt;Addy Osmani&lt;/a&gt;&lt;/p&gt;
    &lt;p&gt;Part of &lt;a href=&quot;http://todomvc.com&quot;&gt;TodoMVC&lt;/a&gt;&lt;/p&gt;
  &lt;/div&gt;</code></pre>
<p>We’ll be populating our todo-list and adding a statistics section with details about what items are left to be completed later on.</p>
<p>So far so good. Now in order to tie this into our Backbone Todo app, we're going to have to go back to the fundamentals - a Todo model.</p>
<h2 id="todo-model">Todo model</h2>
<p>The <code>Todo</code> model is remarkably straightforward. Firstly a todo has two attributes, a <code>title</code> and a <code>completed</code> status that indicates whether it's been completed. These attributes are passed as defaults, as you can see in the example below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> app = app || {};

  <span class="co">// Todo Model</span>
  <span class="co">// ----------</span>
  <span class="co">// Our basic **Todo** model has `title`, `order`, and `completed` attributes.</span>

  <span class="kw">app</span>.<span class="fu">Todo</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({

    <span class="co">// Default attributes for the todo</span>
    <span class="co">// and ensure that each todo created has `title` and `completed` keys.</span>
    <span class="dt">defaults</span>: {
      <span class="dt">title</span>: <span class="ch">&#39;&#39;</span>,
      <span class="dt">completed</span>: <span class="kw">false</span>
    },

    <span class="co">// Toggle the `completed` state of this todo item.</span>
    <span class="dt">toggle</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">save</span>({
        <span class="dt">completed</span>: !<span class="kw">this</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>)
      });
    }

  });</code></pre>
<p>We also have a <code>toggle()</code> function which allows to set whether a Todo item has been completed.</p>
<h2 id="todo-collection">Todo collection</h2>
<p>Next we have our <code>TodoList</code> collection used to group our models. The collection is being extended by localStorage which automatically persists Todo records to HTML5 Local Storage via the Backbone LocalStorage adapter, so they're saved between page requests.</p>
<p>We've then got some static methods, <code>completed()</code> and <code>remaining()</code>, which return an array of unfinished and finished todos respectively.</p>
<p>Finally we have a <code>nextOrder()</code> function, that keeps our Todo items in sequential order as well as a <code>comparator()</code> used to sort items by their insertion order.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
  <span class="co">// Todo Collection</span>
  <span class="co">// ---------------</span>

  <span class="co">// The collection of todos is backed by *localStorage* instead of a remote</span>
  <span class="co">// server.</span>
  <span class="kw">var</span> TodoList = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({

    <span class="co">// Reference to this collection&#39;s model.</span>
    <span class="dt">model</span>: <span class="kw">app</span>.<span class="fu">Todo</span>,

    <span class="co">// Save all of the todo items under the `&quot;todos&quot;` namespace.</span>
    <span class="dt">localStorage</span>: <span class="kw">new</span> Store(<span class="ch">&#39;todos-backbone&#39;</span>),

    <span class="co">// Filter down the list of all todo items that are finished.</span>
    <span class="dt">completed</span>: <span class="kw">function</span>() {
      <span class="kw">return</span> <span class="kw">this</span>.<span class="fu">filter</span>(<span class="kw">function</span>( todo ) {
        <span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>);
      });
    },

    <span class="co">// Filter down the list to only todo items that are still not finished.</span>
    <span class="dt">remaining</span>: <span class="kw">function</span>() {
      <span class="kw">return</span> <span class="kw">this</span>.<span class="fu">without</span>.<span class="fu">apply</span>( <span class="kw">this</span>, <span class="kw">this</span>.<span class="fu">completed</span>() );
    },

    <span class="co">// We keep the Todos in sequential order, despite being saved by unordered</span>
    <span class="co">// GUID in the database. This generates the next order number for new items.</span>
    <span class="dt">nextOrder</span>: <span class="kw">function</span>() {
      <span class="kw">if</span> ( !<span class="kw">this</span>.<span class="fu">length</span> ) {
        <span class="kw">return</span> <span class="dv">1</span>;
      }
      <span class="kw">return</span> <span class="kw">this</span>.<span class="fu">last</span>().<span class="fu">get</span>(<span class="ch">&#39;order&#39;</span>) + <span class="dv">1</span>;
    },

    <span class="co">// Todos are sorted by their original insertion order.</span>
    <span class="dt">comparator</span>: <span class="kw">function</span>( todo ) {
      <span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">get</span>(<span class="ch">&#39;order&#39;</span>);
    }
  });

  <span class="co">// Create our global collection of **Todos**.</span>
  <span class="kw">app</span>.<span class="fu">Todos</span> = <span class="kw">new</span> TodoList();</code></pre>
<h2 id="application-view">Application View</h2>
<p>So let's look at the core of the application's logic, the views. Since each todo has a fair bit of logic associated with it, such as edit in place, we're going to use the element controller pattern - a pattern which consists of two views, one that controls a collection of items, and the other deals with each individual item.</p>
<p>In other words, we're going to have one view <code>AppView</code>, which will be in charge creating new todos, and rendering the initial todo list. Then we'll have another view called TodoView instances of which will be associated with an individual Todo record. Todo instances will be in charge of editing, updating and destroying their associated todo.</p>
<p>To keep thing simple, we'll keep things 'read-only' at the moment, and won't provide any functionality for creating, editing or deleting todos:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
  <span class="co">// The Application</span>
  <span class="co">// ---------------</span>

  <span class="co">// Our overall **AppView** is the top-level piece of UI.</span>
  <span class="kw">app</span>.<span class="fu">AppView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({

    <span class="co">// Instead of generating a new element, bind to the existing skeleton of</span>
    <span class="co">// the App already present in the HTML.</span>
    <span class="dt">el</span>: <span class="ch">&#39;#todoapp&#39;</span>,

    <span class="co">// Our template for the line of statistics at the bottom of the app.</span>
    <span class="dt">statsTemplate</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#stats-template&#39;</span>).<span class="fu">html</span>() ),

    <span class="co">// At initialization we bind to the relevant events on the `Todos`</span>
    <span class="co">// collection, when items are added or changed. Kick things off by</span>
    <span class="co">// loading any preexisting todos that might be saved in *localStorage*.</span>
    <span class="dt">initialize</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#new-todo&#39;</span>);
      <span class="kw">this</span>.<span class="fu">allCheckbox</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#toggle-all&#39;</span>)[<span class="dv">0</span>];
      <span class="kw">this</span>.$<span class="fu">footer</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#footer&#39;</span>);
      <span class="kw">this</span>.$<span class="fu">main</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#main&#39;</span>);

      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>( <span class="ch">&#39;add&#39;</span>, <span class="kw">this</span>.<span class="fu">addOne</span>, <span class="kw">this</span> );
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>( <span class="ch">&#39;reset&#39;</span>, <span class="kw">this</span>.<span class="fu">addAll</span>, <span class="kw">this</span> );
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>( <span class="ch">&#39;all&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span> );

      <span class="kw">app.Todos</span>.<span class="fu">fetch</span>();
    },

    <span class="co">// Re-rendering the App just means refreshing the statistics -- the rest</span>
    <span class="co">// of the app doesn&#39;t change.</span>
    <span class="dt">render</span>: <span class="kw">function</span>() {
      <span class="kw">var</span> completed = <span class="kw">app.Todos</span>.<span class="fu">completed</span>().<span class="fu">length</span>;
      <span class="kw">var</span> remaining = <span class="kw">app.Todos</span>.<span class="fu">remaining</span>().<span class="fu">length</span>;

      <span class="kw">if</span> ( <span class="kw">app.Todos</span>.<span class="fu">length</span> ) {
        <span class="kw">this</span>.$<span class="fu">main</span>.<span class="fu">show</span>();
        <span class="kw">this</span>.$<span class="fu">footer</span>.<span class="fu">show</span>();

        <span class="kw">this</span>.$<span class="fu">footer</span>.<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">statsTemplate</span>({
          <span class="dt">completed</span>: completed,
          <span class="dt">remaining</span>: remaining
        }));

      } <span class="kw">else</span> {
        <span class="kw">this</span>.$<span class="fu">main</span>.<span class="fu">hide</span>();
        <span class="kw">this</span>.$<span class="fu">footer</span>.<span class="fu">hide</span>();
      }

      <span class="kw">this</span>.<span class="fu">allCheckbox</span>.<span class="fu">checked</span> = !remaining;
    },

    <span class="co">// Add a single todo item to the list by creating a view for it, and</span>
    <span class="co">// appending its element to the `&lt;ul&gt;`.</span>
    <span class="dt">addOne</span>: <span class="kw">function</span>( todo ) {
      <span class="kw">var</span> view = <span class="kw">new</span> <span class="kw">app</span>.<span class="fu">TodoView</span>({ <span class="dt">model</span>: todo });
      $(<span class="ch">&#39;#todo-list&#39;</span>).<span class="fu">append</span>( <span class="kw">view</span>.<span class="fu">render</span>().<span class="fu">el</span> );
    },

    <span class="co">// Add all items in the **Todos** collection at once.</span>
    <span class="dt">addAll</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$(<span class="ch">&#39;#todo-list&#39;</span>).<span class="fu">html</span>(<span class="ch">&#39;&#39;</span>);
      <span class="kw">app.Todos</span>.<span class="fu">each</span>(<span class="kw">this</span>.<span class="fu">addOne</span>, <span class="kw">this</span>);
    }

  });</code></pre>
<p>You can see we've got a couple of things going on, an el (element), a <code>statsTemplate</code>, a constructor function and several view specific methods. On the left of the el: key is a DOM element selector for the element with ID <code>todoapp</code>. The value of this is just a string and Backbone will create a reference pointing to any element matching the selector #todoapp, where here it will be the <code>&lt;section id=”todoapp /&gt;</code> element, defined in the HTML section earlier.</p>
<p>In a nutshell this means we can now refer to this.el in our controller, which points to the <code>&lt;section class=&quot;todoapp&quot; /&gt;</code> element. As you can see, we're referring to el in the <code>addOne()</code> function, appending an element to the list.</p>
<p>Now let's take a look at the constructor function. It's binding to several events on the Todo model, such as add, reset and all. Since we're delegating handling of updates and deletes to the <code>TodoView</code> view, we don't need to to worry about that here. The two pieces of logic are:</p>
<ul>
<li><p>When a new todo is created, the <code>add</code> event will be fired, calling <code>addAll()</code>. This iterates over all of the Todos currently in our collection and fires <code>addOne()</code> for each item.</p></li>
<li><p><code>addOne()</code> instantiates the TodoView view, rendering it and appending the resultant element to our Todo list.</p></li>
<li><p>When a <code>reset</code> event is called (i.e. we wish to update the collection in bulk such as when the Todos have been loaded from Local Storage), <code>addAll()</code> is similarly called again.</p></li>
</ul>
<p>We can then add in the logic for creating new todos, editing them and filtering them based on whether they are complete.</p>
<ul>
<li>events: We define an events hash containing declarative callbacks for our DOM events.</li>
<li><code>createOnEnter()</code>: When a user hits return inside the <code>&lt;input/&gt;</code> field, this creates a new Todo item and resets the main <code>&lt;input/&gt;</code> field value to prepare it for the next entry.</li>
<li><code>clearCompleted()</code>: Removes the items in the todo list that have been marked as completed</li>
<li><code>toggleAllComplete()</code>: Allows a user to set all of the items in the todo list to completed.</li>
<li><code>initialize()</code>: We bind a callback for a change:completed event, letting us know a change has been made as well to an existing todo item We also bind a callback for a filter event, which works a little similar to addOne() and addAll(). It’s responsibility is to toggle what todo items are visible based on the filter currently selected in the UI (all, completed or remaining) through filterOne() and filterAll().</li>
<li><code>render()</code>: We add some conditional CSS styling based on the filter currently selected so that the route that has been selected is highlighted</li>
<li><code>createOnEnter()</code>: Creates a new Todo model which persists in localStorage when a user hits return. This creates the model via newAttributes(), which is an object literal composed of the title, order and completed state of the new item being added.</li>
<li><code>clearCompleted()</code>: Clears all the todo items that have been marked as complete</li>
</ul>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="co">// The Application</span>
  <span class="co">// ---------------</span>

  <span class="co">// Our overall **AppView** is the top-level piece of UI.</span>
  <span class="kw">app</span>.<span class="fu">AppView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({

    <span class="co">// Instead of generating a new element, bind to the existing skeleton of</span>
    <span class="co">// the App already present in the HTML.</span>
    <span class="dt">el</span>: <span class="ch">&#39;#todoapp&#39;</span>,

    <span class="co">// Our template for the line of statistics at the bottom of the app.</span>
    <span class="dt">statsTemplate</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#stats-template&#39;</span>).<span class="fu">html</span>() ),

    <span class="co">// Delegated events for creating new items, and clearing completed ones.</span>
    <span class="dt">events</span>: {
      <span class="ch">&#39;keypress #new-todo&#39;</span>: <span class="ch">&#39;createOnEnter&#39;</span>,
      <span class="ch">&#39;click #clear-completed&#39;</span>: <span class="ch">&#39;clearCompleted&#39;</span>,
      <span class="ch">&#39;click #toggle-all&#39;</span>: <span class="ch">&#39;toggleAllComplete&#39;</span>
    },

    <span class="co">// At initialization we bind to the relevant events on the `Todos`</span>
    <span class="co">// collection, when items are added or changed. Kick things off by</span>
    <span class="co">// loading any preexisting todos that might be saved in *localStorage*.</span>
    <span class="dt">initialize</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#new-todo&#39;</span>);
      <span class="kw">this</span>.<span class="fu">allCheckbox</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#toggle-all&#39;</span>)[<span class="dv">0</span>];
      <span class="kw">this</span>.$<span class="fu">footer</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#footer&#39;</span>);
      <span class="kw">this</span>.$<span class="fu">main</span> = <span class="kw">this</span>.$(<span class="ch">&#39;#main&#39;</span>);

      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>( <span class="ch">&#39;add&#39;</span>, <span class="kw">this</span>.<span class="fu">addAll</span>, <span class="kw">this</span> );
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>( <span class="ch">&#39;reset&#39;</span>, <span class="kw">this</span>.<span class="fu">addAll</span>, <span class="kw">this</span> );
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>(<span class="ch">&#39;change:completed&#39;</span>, <span class="kw">this</span>.<span class="fu">filterOne</span>, <span class="kw">this</span>);
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>(<span class="st">&quot;filter&quot;</span>, <span class="kw">this</span>.<span class="fu">filterAll</span>, <span class="kw">this</span>);

      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">on</span>( <span class="ch">&#39;all&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span> );

      <span class="kw">app.Todos</span>.<span class="fu">fetch</span>();
    },

    <span class="co">// Re-rendering the App just means refreshing the statistics -- the rest</span>
    <span class="co">// of the app doesn&#39;t change.</span>
    <span class="dt">render</span>: <span class="kw">function</span>() {
      <span class="kw">var</span> completed = <span class="kw">app.Todos</span>.<span class="fu">completed</span>().<span class="fu">length</span>;
      <span class="kw">var</span> remaining = <span class="kw">app.Todos</span>.<span class="fu">remaining</span>().<span class="fu">length</span>;

      <span class="kw">if</span> ( <span class="kw">app.Todos</span>.<span class="fu">length</span> ) {
        <span class="kw">this</span>.$<span class="fu">main</span>.<span class="fu">show</span>();
        <span class="kw">this</span>.$<span class="fu">footer</span>.<span class="fu">show</span>();

        <span class="kw">this</span>.$<span class="fu">footer</span>.<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">statsTemplate</span>({
          <span class="dt">completed</span>: completed,
          <span class="dt">remaining</span>: remaining
        }));

        <span class="kw">this</span>.$(<span class="ch">&#39;#filters li a&#39;</span>)
          .<span class="fu">removeClass</span>(<span class="ch">&#39;selected&#39;</span>)
          .<span class="fu">filter</span>(<span class="ch">&#39;[href=&quot;#/&#39;</span> + ( <span class="kw">app</span>.<span class="fu">TodoFilter</span> || <span class="ch">&#39;&#39;</span> ) + <span class="ch">&#39;&quot;]&#39;</span>)
          .<span class="fu">addClass</span>(<span class="ch">&#39;selected&#39;</span>);
      } <span class="kw">else</span> {
        <span class="kw">this</span>.$<span class="fu">main</span>.<span class="fu">hide</span>();
        <span class="kw">this</span>.$<span class="fu">footer</span>.<span class="fu">hide</span>();
      }

      <span class="kw">this</span>.<span class="fu">allCheckbox</span>.<span class="fu">checked</span> = !remaining;
    },

    <span class="co">// Add a single todo item to the list by creating a view for it, and</span>
    <span class="co">// appending its element to the `&lt;ul&gt;`.</span>
    <span class="dt">addOne</span>: <span class="kw">function</span>( todo ) {
      <span class="kw">var</span> view = <span class="kw">new</span> <span class="kw">app</span>.<span class="fu">TodoView</span>({ <span class="dt">model</span>: todo });
      $(<span class="ch">&#39;#todo-list&#39;</span>).<span class="fu">append</span>( <span class="kw">view</span>.<span class="fu">render</span>().<span class="fu">el</span> );
    },

    <span class="co">// Add all items in the **Todos** collection at once.</span>
    <span class="dt">addAll</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$(<span class="ch">&#39;#todo-list&#39;</span>).<span class="fu">html</span>(<span class="ch">&#39;&#39;</span>);
      <span class="kw">app.Todos</span>.<span class="fu">each</span>(<span class="kw">this</span>.<span class="fu">addOne</span>, <span class="kw">this</span>);
    },

    <span class="dt">filterOne </span>: <span class="kw">function</span> (todo) {
      <span class="kw">todo</span>.<span class="fu">trigger</span>(<span class="st">&quot;visible&quot;</span>);
    },

    <span class="dt">filterAll </span>: <span class="kw">function</span> () {
      <span class="kw">app.Todos</span>.<span class="fu">each</span>(<span class="kw">this</span>.<span class="fu">filterOne</span>, <span class="kw">this</span>);
    },

    <span class="co">// Generate the attributes for a new Todo item.</span>
    <span class="dt">newAttributes</span>: <span class="kw">function</span>() {
      <span class="kw">return</span> {
        <span class="dt">title</span>: <span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">val</span>().<span class="fu">trim</span>(),
        <span class="dt">order</span>: <span class="kw">app.Todos</span>.<span class="fu">nextOrder</span>(),
        <span class="dt">completed</span>: <span class="kw">false</span>
      };
    },

    <span class="co">// If you hit return in the main input field, create new **Todo** model,</span>
    <span class="co">// persisting it to *localStorage*.</span>
    <span class="dt">createOnEnter</span>: <span class="kw">function</span>( e ) {
      <span class="kw">if</span> ( <span class="kw">e</span>.<span class="fu">which</span> !== ENTER_KEY || !<span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">val</span>().<span class="fu">trim</span>() ) {
        <span class="kw">return</span>;
      }

      <span class="kw">app.Todos</span>.<span class="fu">create</span>( <span class="kw">this</span>.<span class="fu">newAttributes</span>() );
      <span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">val</span>(<span class="ch">&#39;&#39;</span>);
    },

    <span class="co">// Clear all completed todo items, destroying their models.</span>
    <span class="dt">clearCompleted</span>: <span class="kw">function</span>() {
      <span class="kw">_</span>.<span class="fu">each</span>( <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">completed</span>(), <span class="kw">function</span>( todo ) {
        <span class="kw">todo</span>.<span class="fu">destroy</span>();
      });

      <span class="kw">return</span> <span class="kw">false</span>;
    },

    <span class="dt">toggleAllComplete</span>: <span class="kw">function</span>() {
      <span class="kw">var</span> completed = <span class="kw">this</span>.<span class="fu">allCheckbox</span>.<span class="fu">checked</span>;

      <span class="kw">app.Todos</span>.<span class="fu">each</span>(<span class="kw">function</span>( todo ) {
        <span class="kw">todo</span>.<span class="fu">save</span>({
          <span class="ch">&#39;completed&#39;</span>: completed
        });
      });
    }
  });</code></pre>
<h2 id="setup">Setup</h2>
<p>So now we have two views: <code>AppView</code> and <code>TodoView</code>. The former needs to get instantiated when the page loads, so some code actually gets run. You can do this simply enough, by using jQuery's <code>ready()</code> utility, which will execute a function when the DOM's loaded.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> app = app || {};
<span class="kw">var</span> ENTER_KEY = <span class="dv">13</span>;

$(<span class="kw">function</span>() {

  <span class="co">// Kick things off by creating the **App**.</span>
  <span class="kw">new</span> <span class="kw">app</span>.<span class="fu">AppView</span>();

});</code></pre>
<h2 id="creating-new-todos">Creating new todos</h2>
<p>It's all very good creating todos from the console, but we can hardly expect our users to do that. Let's hook up the todo creation section to provide a better interface. All the HTML is already there (in index.html); all we have to do is add some event listeners to that section, creating some todos.</p>
<img src="img/todoview.png" width="590px"/>
<p>Let’s look at the <code>TodoView</code> view. This will be in charge of individual Todo records, making sure the view updates then the todo does.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
  <span class="co">// Todo Item View</span>
  <span class="co">// --------------</span>

  <span class="co">// The DOM element for a todo item...</span>
  <span class="kw">app</span>.<span class="fu">TodoView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({

    <span class="co">//... is a list tag.</span>
    <span class="dt">tagName</span>: <span class="ch">&#39;li&#39;</span>,

    <span class="co">// Cache the template function for a single item.</span>
    <span class="dt">template</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#item-template&#39;</span>).<span class="fu">html</span>() ),

    <span class="co">// The DOM events specific to an item.</span>
    <span class="dt">events</span>: {
      <span class="ch">&#39;dblclick label&#39;</span>: <span class="ch">&#39;edit&#39;</span>,
      <span class="ch">&#39;keypress .edit&#39;</span>: <span class="ch">&#39;updateOnEnter&#39;</span>,
      <span class="ch">&#39;blur .edit&#39;</span>: <span class="ch">&#39;close&#39;</span>
    },

    <span class="co">// The TodoView listens for changes to its model, re-rendering. Since there&#39;s</span>
    <span class="co">// a one-to-one correspondence between a **Todo** and a **TodoView** in this</span>
    <span class="co">// app, we set a direct reference on the model for convenience.</span>
    <span class="dt">initialize</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>( <span class="ch">&#39;change&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span> );
    },

    <span class="co">// Re-render the titles of the todo item.</span>
    <span class="dt">render</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">template</span>( <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>() ) );
      <span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">&#39;.edit&#39;</span>);
      <span class="kw">return</span> <span class="kw">this</span>;
    },

    <span class="co">// Switch this view into `&quot;editing&quot;` mode, displaying the input field.</span>
    <span class="dt">edit</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">addClass</span>(<span class="ch">&#39;editing&#39;</span>);
      <span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">focus</span>();
    },

    <span class="co">// Close the `&quot;editing&quot;` mode, saving changes to the todo.</span>
    <span class="dt">close</span>: <span class="kw">function</span>() {
      <span class="kw">var</span> value = <span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">val</span>().<span class="fu">trim</span>();

      <span class="kw">if</span> ( value ) {
        <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">save</span>({ <span class="dt">title</span>: value });
      }

      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">removeClass</span>(<span class="ch">&#39;editing&#39;</span>);
    },

    <span class="co">// If you hit `enter`, we&#39;re through editing the item.</span>
    <span class="dt">updateOnEnter</span>: <span class="kw">function</span>( e ) {
      <span class="kw">if</span> ( <span class="kw">e</span>.<span class="fu">which</span> === ENTER_KEY ) {
        <span class="kw">this</span>.<span class="fu">close</span>();
      }
    }
  });</code></pre>
<p>In the <code>initialize()</code> constructor, we're setting up a listener to the todo model’s change event. In other words, when the todo updates, we want to re-render the view to reflect its changes.</p>
<p>In the <code>render()</code> method, we're rendering an Underscore.js JavaScript template, called <code>#item-template</code>, which we’ve previously compiled into this.template using Underscore’s <code>_.template()</code> method. This returns a piece of HTML that we're using to replace the view’s current element. In other words, the rendered template is now present under <code>this.el</code>, and can be appended to the todo list.</p>
<p>Our events hash includes three callbacks:</p>
<ul>
<li><code>edit()</code>: Changes the current view into editing mode when a user double-clicks on an existing item in the todo list. This allows them to change the existing value of the item’s title attribute</li>
<li><code>updateOnEnter()</code>: checks that the user has hit the return/enter key and executes the close() function.</li>
<li><code>close()</code>: This trims the value of the current text in our <code>&lt;input/&gt;</code> field, ensuring that we don’t process it further if it contains no text (e.g ‘’). If a valid value has been provided, we save the changes to the current todo model and close editing mode, by removing the corresponding CSS class.</li>
</ul>
<h2 id="in-action">In action</h2>
<p>Now we've gone far enough without checking that things work as they should. Open up index.html and, if everything's going to plan, you shouldn't see any errors in the console. The todo list will be blank (we haven't created any todos yet), and the todo-list won't work, as we haven't yet hooked it up. However, we can create a Todo from the console.</p>
<p>Type in: <code>window.app.Todos.create({ title: ‘My first Todo item});</code> and hit return.</p>
<img src="img/todoconsole.png" width="700px"/>
<p>Once you've run the above in the console, we should be looking at a brand new todo in the list of todos. Notice that if you refresh the page, the todo still persists using Local Storage.</p>
<h2 id="templates">Templates</h2>
<p>The <code>#item-template</code> used in the <code>TodoView</code> view needs defining, so let's do that. One way of including templates in the page is by using custom script tags. These don't get evaluated by the browser, which just interprets them as plain text. Underscore micro-templating can then access the templates, rendering pieces of HTML.</p>
<pre class="sourceCode html"><code class="sourceCode html"> <span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/template&quot;</span><span class="ot"> id=</span><span class="st">&quot;item-template&quot;</span><span class="kw">&gt;</span>
    &lt;div class=<span class="st">&quot;view&quot;</span>&gt;
      &lt;input class=<span class="st">&quot;toggle&quot;</span> type=<span class="st">&quot;checkbox&quot;</span> &lt;%= completed ? <span class="ch">&#39;checked&#39;</span> : <span class="ch">&#39;&#39;</span> %&gt;&gt;
      &lt;label&gt;&lt;%- title %&gt;&lt;/label&gt;
      &lt;button class=<span class="st">&quot;destroy&quot;</span>&gt;&lt;/button&gt;
    &lt;/div&gt;
    &lt;input class=<span class="st">&quot;edit&quot;</span> value=<span class="st">&quot;</span>&lt;%- <span class="st">title</span> %&gt;<span class="st">&quot;</span>&gt;
  <span class="kw">&lt;/script&gt;</span></code></pre>
<p>The template tags demonstrated above, such as <code>&lt;%=</code> , are specific to Underscore.js, and documented on the Underscore site. In your own applications, you have a choice of template libraries, such as Mustache or Handlebars. Use whichever you prefer, Backbone doesn't mind.</p>
<p>Now when <code>_.template( $('#item-template').html() )</code> is called in the <code>TodoView</code> view our template will render correctly.</p>
<p>We also need to define #stats-template template we use to display how many items have been completed, as well as allowing the user to clear these items.</p>
<pre class="sourceCode html"><code class="sourceCode html"> <span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/template&quot;</span><span class="ot"> id=</span><span class="st">&quot;stats-template&quot;</span><span class="kw">&gt;</span>
    &lt;span id=<span class="st">&quot;todo</span>-<span class="st">count&quot;</span>&gt;&lt;strong&gt;&lt;%= remaining %&gt;&lt;/strong&gt; &lt;%= remaining === <span class="dv">1</span> ? <span class="ch">&#39;item&#39;</span> : <span class="ch">&#39;items&#39;</span> %&gt; left&lt;/span&gt;
    &lt;ul id=<span class="st">&quot;filters&quot;</span>&gt;
      &lt;li&gt;
        &lt;a class=<span class="st">&quot;selected&quot;</span> href=<span class="st">&quot;</span>#/<span class="st">&quot;</span>&gt;All&lt;/a&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;a href=<span class="st">&quot;</span>#/<span class="st">active&quot;</span>&gt;Active&lt;/a&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;a href=<span class="st">&quot;</span>#/<span class="st">completed&quot;</span>&gt;Completed&lt;/a&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
    &lt;% <span class="kw">if</span> (completed) { %&gt;
    &lt;button id=<span class="st">&quot;clear</span>-<span class="st">completed&quot;</span>&gt;Clear completed (&lt;%= completed %&gt;)&lt;/button&gt;
    &lt;% } %&gt;
  <span class="kw">&lt;/script&gt;</span></code></pre>
<h2 id="in-action-1">In action</h2>
<p>Now refresh index.html to see the fruits of our labour. We should be able to type a todo name, and press return to submit the form, creating a new todo.</p>
<div class="figure">
<img src="img/todocompleted.png" /><p class="caption"></p>
</div>
<p>Excellent, we're making great progress, but how about completing and deleting todos?</p>
<h2 id="completing-deleting-todos">Completing &amp; deleting todos</h2>
<p>So the next part of our tutorial is going to cover completing and deleting todos. These two actions are specific to each Todo item, so we need to add this functionality to the TodoView view.</p>
<p>The key part of this is the two event handlers we've added, a togglecompleted event on the todo's checkbox, and a click event on the todo's <code>&lt;button class=&quot;destroy&quot; /&gt;</code> button.</p>
<p>The checkbox's togglecompleted event invokes the toggle() function, which toggles the todos's completed status, then resaving the todo - very straightforward! The button's click event invokes <code>clear()</code>, which will simply destroy the todo.</p>
<p>That's all there is to it. Since we're binding to the change event, whenever the todo changes the view will automatically be re-rendered, checking or un-checking the checkbox as appropriate. Similarly, when the todo is destroyed, the model's <code>destroy()</code> function will be called, removing the todo from the view as we’re binding to the destroy event too.</p>
<p>One more piece to mention is that we’ve also binded to a visible event to handle the visibility state of the todo item. This is used in conjunction with the filtering in our routes and collections so that we only display an item if its completed state falls in line with the current filter.</p>
<p>This tutorial is long enough as is, so we won't go into in-place editing or updating. If you want an example of that, see the <a href="https://github.com/addyosmani/todomvc/tree/master/architecture-examples/backbone/">complete source</a>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
  <span class="co">// Todo Item View</span>
  <span class="co">// --------------</span>

  <span class="co">// The DOM element for a todo item...</span>
  <span class="kw">app</span>.<span class="fu">TodoView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({

    <span class="co">//... is a list tag.</span>
    <span class="dt">tagName</span>: <span class="ch">&#39;li&#39;</span>,

    <span class="co">// Cache the template function for a single item.</span>
    <span class="dt">template</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#item-template&#39;</span>).<span class="fu">html</span>() ),

    <span class="co">// The DOM events specific to an item.</span>
    <span class="dt">events</span>: {
      <span class="ch">&#39;click .toggle&#39;</span>: <span class="ch">&#39;togglecompleted&#39;</span>,
      <span class="ch">&#39;dblclick label&#39;</span>: <span class="ch">&#39;edit&#39;</span>,
      <span class="ch">&#39;click .destroy&#39;</span>: <span class="ch">&#39;clear&#39;</span>,
      <span class="ch">&#39;keypress .edit&#39;</span>: <span class="ch">&#39;updateOnEnter&#39;</span>,
      <span class="ch">&#39;blur .edit&#39;</span>: <span class="ch">&#39;close&#39;</span>
    },

    <span class="co">// The TodoView listens for changes to its model, re-rendering. Since there&#39;s</span>
    <span class="co">// a one-to-one correspondence between a **Todo** and a **TodoView** in this</span>
    <span class="co">// app, we set a direct reference on the model for convenience.</span>
    <span class="dt">initialize</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>( <span class="ch">&#39;change&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span> );
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>( <span class="ch">&#39;destroy&#39;</span>, <span class="kw">this</span>.<span class="fu">remove</span>, <span class="kw">this</span> );
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>( <span class="ch">&#39;visible&#39;</span>, <span class="kw">this</span>.<span class="fu">toggleVisible</span>, <span class="kw">this</span> );
    },

    <span class="co">// Re-render the titles of the todo item.</span>
    <span class="dt">render</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">template</span>( <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>() ) );
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">toggleClass</span>( <span class="ch">&#39;completed&#39;</span>, <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>) );

      <span class="kw">this</span>.<span class="fu">toggleVisible</span>();
      <span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">&#39;.edit&#39;</span>);
      <span class="kw">return</span> <span class="kw">this</span>;
    },

    <span class="dt">toggleVisible </span>: <span class="kw">function</span> () {
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">toggleClass</span>( <span class="ch">&#39;hidden&#39;</span>, <span class="kw">this</span>.<span class="fu">isHidden</span>());
    },

    <span class="dt">isHidden </span>: <span class="kw">function</span> () {
      <span class="kw">var</span> isCompleted = <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>);
      <span class="kw">return</span> ( <span class="co">// hidden cases only</span>
        (!isCompleted &amp;&amp; <span class="kw">app</span>.<span class="fu">TodoFilter</span> === <span class="ch">&#39;completed&#39;</span>)
        || (isCompleted &amp;&amp; <span class="kw">app</span>.<span class="fu">TodoFilter</span> === <span class="ch">&#39;active&#39;</span>)
      );
    },

    <span class="co">// Toggle the `&quot;completed&quot;` state of the model.</span>
    <span class="dt">togglecompleted</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toggle</span>();
    },

    <span class="co">// Switch this view into `&quot;editing&quot;` mode, displaying the input field.</span>
    <span class="dt">edit</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">addClass</span>(<span class="ch">&#39;editing&#39;</span>);
      <span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">focus</span>();
    },

    <span class="co">// Close the `&quot;editing&quot;` mode, saving changes to the todo.</span>
    <span class="dt">close</span>: <span class="kw">function</span>() {
      <span class="kw">var</span> value = <span class="kw">this</span>.<span class="fu">input</span>.<span class="fu">val</span>().<span class="fu">trim</span>();

      <span class="kw">if</span> ( value ) {
        <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">save</span>({ <span class="dt">title</span>: value });
      } <span class="kw">else</span> {
        <span class="kw">this</span>.<span class="fu">clear</span>();
      }

      <span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">removeClass</span>(<span class="ch">&#39;editing&#39;</span>);
    },

    <span class="co">// If you hit `enter`, we&#39;re through editing the item.</span>
    <span class="dt">updateOnEnter</span>: <span class="kw">function</span>( e ) {
      <span class="kw">if</span> ( <span class="kw">e</span>.<span class="fu">which</span> === ENTER_KEY ) {
        <span class="kw">this</span>.<span class="fu">close</span>();
      }
    },

    <span class="co">// Remove the item, destroy the model from *localStorage* and delete its view.</span>
    <span class="dt">clear</span>: <span class="kw">function</span>() {
      <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">destroy</span>();
    }
  });</code></pre>
<h2 id="todo-routing">Todo routing</h2>
<p>Finally, we move on to routing, which will allow us to easily bookmark the list of items that are active as well as those which have been completed. We’ll be supporting the following routes:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">#/ (all - <span class="kw">default</span>)
#/active
#/completed</code></pre>
<img src="img/todorouting.png" width="700px"/>
<p>When the route changes the todo list will be filtered on a model level and the selected class on the filter links will be toggled. When an item is updated while in a filtered state, it will be updated accordingly. E.g. if the filter is active and the item is checked, it will be hidden. The active filter is persisted on reload.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
  <span class="co">// Todo Router</span>
  <span class="co">// ----------</span>

  <span class="kw">var</span> Workspace = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
    <span class="dt">routes</span>:{
      <span class="ch">&#39;*filter&#39;</span>: <span class="ch">&#39;setFilter&#39;</span>
    },

    <span class="dt">setFilter</span>: <span class="kw">function</span>( param ) {
      <span class="co">// Set the current filter to be used</span>
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">TodoFilter</span> = <span class="kw">param</span>.<span class="fu">trim</span>() || <span class="ch">&#39;&#39;</span>;

      <span class="co">// Trigger a collection filter event, causing hiding/unhiding</span>
      <span class="co">// of Todo view items</span>
      <span class="kw">window</span>.<span class="fu">app</span>.<span class="fu">Todos</span>.<span class="fu">trigger</span>(<span class="ch">&#39;filter&#39;</span>);
    }
  });

  <span class="kw">app</span>.<span class="fu">TodoRouter</span> = <span class="kw">new</span> Workspace();
  <span class="kw">Backbone.history</span>.<span class="fu">start</span>();</code></pre>
<p>As we can see in the line <code>window.app.Todos.trigger('filter')</code>, once a string filter has been set, we simply trigger our filter at a collection level to toggle which items are displayed and which of those are hidden.</p>
<p>Finally, we call <code>Backbone.history.start()</code> to route the initial URL during page load.</p>
<h2 id="conclusions">Conclusions</h2>
<p>We’ve now learned how to build our first complete Backbone.js application. The app can be viewed online at any time and the sources are readily available via <a href="http://www.todomvc.com">TodoMVC</a>.</p>
<p>Later on in the book, we’ll learn how to further modularize this application using Require.js, swap out our persistence layer to a database back-end and finally unit test the application with a few different testing frameworks.</p>
<h1 id="backbone-boilerplate-and-grunt-bbb"><a name="backboneboilerplate">Backbone Boilerplate And Grunt-BBB</a></h1>
<p><a href="https://github.com/tbranyen/backbone-boilerplate/">Backbone Boilerplate</a> is an excellent set of best practices and utilities for building Backbone.js applications, created by Backbone contributor <a href="https://github.com/tbranyen">Tim Branyen</a>. He organized this boilerplate out of the gotchas, pitfalls and common tasks he ran into over a year of heavily using Backbone to build apps at Bocoup. This includes apps such <a href="http://startupdatatrends">StartupDataTrends.com</a>.</p>
<p>With scaffolding and built in build tasks that take care of minification, concatentation, server, template compilation and more, Backbone Boilerplate (and sister project <a href="https://github.com/backbone-boilerplate/grunt-bbb">Grunt-BBB</a>) are an excellent choice for developers of all levels. I heavily recommend using them as they will give you an enormous start when it comes to getting setup for development. They also have some great inline documentation which is also another excellent time-saver.</p>
<p>By default, Backbone Boilerplate provides you with:</p>
<ul>
<li>Backbone, <a href="https://github.com/bestiejs/lodash">Lodash</a> (an <a href="http://underscorejs.org/">Underscore.js</a> alternative) and <a href="http://jquery.com">jQuery</a> with an <a href="http://html5boilerplate.com">HTML5 Boilerplate</a> foundation</li>
<li>Boilerplate module code</li>
<li>A Windows/Mac/Linux build tool for template precompilation and, concatenation &amp; minification of all your libraries, application code and CSS</li>
<li>Scaffolding support (via grunt-bbb - [B]ackbone [B]oilerplate [B]uild) so you have to spend minimal time writing boilerplate for modules, collections and so on.</li>
<li>A Lightweight node.js webserver</li>
<li>Numerous other Backbone.js snippets for making your life easier</li>
</ul>
<h2 id="getting-started">Getting Started</h2>
<h3 id="backbone-boilerplate">Backbone Boilerplate</h3>
<p>We can use Boilerplate to easily begin creating an application, but first, we'll need to install it. This can be done by grabbing the latest version of it by cloning the Boilerplate repo directly:</p>
<pre class="shell"><code>$ git clone git://github.com/tbranyen/backbone-boilerplate.git</code></pre>
<p>or alternatively, just fetching the latest tarball as follows:</p>
<pre class="shell"><code>curl -C - -O https://github.com/tbranyen/backbone-boilerplate/zipball/master</code></pre>
<h3 id="grunt-bbb">Grunt-BBB</h3>
<p>As Tim covers in the Boilerplate docs, we have to install <a href="http://gruntjs.org">Grunt</a> if we want to use the build tools and grunt-bbb helpers he recommends.</p>
<p>Grunt is an excellent Node-based JavaScript build tool by another <a href="http://bocoup.com">Bocoup</a> developer (<a href="http://benalman.com">Ben Alman</a>). Think of it as similar to <a href="http://ant.apache.org/">Ant</a> or <a href="https://github.com/jimweirich/rake">Rake</a>. The grunt-bbb helper is also useful to have as it provides several Backbone-specific utilities for scaffolding out your project, without the need to write boilerplate yourself.</p>
<p>To install grunt and grunt-bbb via NPM:</p>
<pre class="shell"><code># first run
$ npm install -g grunt

# followed by
$ npm install -g bbb

# Create a new project
bbb init</code></pre>
<p>That's it. We should now be good to go.</p>
<p>A typical workflow for using grunt-bbb, which we can use later on is:</p>
<ul>
<li>Initialize a new project (<code>bbb init</code>)</li>
<li>Add new modules and templates (<code>bbb init:module</code>)</li>
<li>Develop using the built in server (<code>bbb server</code>)</li>
<li>Run the build tool (<code>bbb build</code>)</li>
<li>Deploy and map to production assets (using <code>bbb release</code>)</li>
</ul>
<h2 id="creating-a-new-project">Creating a new project</h2>
<p>Let's create a new folder for our project and run <code>bbb init</code> to kick things off. If everything has been correctly installed, this will sub out some project directories and files for us. Let's review what is generated.</p>
<h3 id="index.html">index.html</h3>
<p>This is a fairly standard stripped-down HTML5 Boilerplate foundation with the notable exception of including <a href="http://requirejs.org">Require.js</a> at the bottom of the page.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="er">&lt;</span>!doctype html&gt;
<span class="kw">&lt;html</span><span class="ot"> lang=</span><span class="st">&quot;en&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;head&gt;</span>
  <span class="kw">&lt;meta</span><span class="ot"> charset=</span><span class="st">&quot;utf-8&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;meta</span><span class="ot"> http-equiv=</span><span class="st">&quot;X-UA-Compatible&quot;</span><span class="ot"> content=</span><span class="st">&quot;IE=edge,chrome=1&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;meta</span><span class="ot"> name=</span><span class="st">&quot;viewport&quot;</span><span class="ot"> content=</span><span class="st">&quot;width=device-width,initial-scale=1&quot;</span><span class="kw">&gt;</span>

  <span class="kw">&lt;title&gt;</span>Backbone Boilerplate<span class="kw">&lt;/title&gt;</span>

  <span class="co">&lt;!-- Application styles. --&gt;</span>
  <span class="kw">&lt;link</span><span class="ot"> rel=</span><span class="st">&quot;stylesheet&quot;</span><span class="ot"> href=</span><span class="st">&quot;/assets/css/index.css&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/head&gt;</span>

<span class="kw">&lt;body&gt;</span>
  <span class="co">&lt;!-- Main container. --&gt;</span>
  <span class="kw">&lt;div</span><span class="ot"> role=</span><span class="st">&quot;main&quot;</span><span class="ot"> id=</span><span class="st">&quot;main&quot;</span><span class="kw">&gt;&lt;/div&gt;</span>

  <span class="co">&lt;!-- Application source. --&gt;</span>
  <span class="kw">&lt;script</span><span class="ot"> data-main=</span><span class="st">&quot;/app/config&quot;</span><span class="ot"> src=</span><span class="st">&quot;/assets/js/libs/require.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>Require.js is an <a href="https://github.com/amdjs/amdjs-api/wiki/AMD">AMD</a> (Asynchronous Module Definition) module and script loader, which will assist us with managing the modules in our application. We'll be covering it in a lot more detail later on in the book, but for now, let's cover at a high-level what this particular block does:</p>
<pre><code>&lt;script data-main=&quot;app/config&quot; src=&quot;/assets/js/libs/require.js&quot;&gt;&lt;/script&gt;</code></pre>
<p>The <code>data-main</code> attribute is used to inform Require.js to load <code>app/config.js</code> (a configuration object) after it has finished loading itself. You'll notice that we've omitted the <code>.js</code> extension here as require.js can automatically add this for us, however it will respect your paths if we do choose to include it regardless. Let's now look at the config file being referenced.</p>
<h3 id="config.js">config.js</h3>
<p>A Require.js configuration object allows us to specify aliases and paths for dependencies we're likely to reference often (e.g jQuery), bootstrap properties like our base application URL and <code>shim</code> libraries that don't support AMD natively.</p>
<p>This is what the config file in Backbone Boilerplate looks like:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Set the require.js configuration for your application.</span>
<span class="kw">require</span>.<span class="fu">config</span>({

  <span class="co">// Initialize the application with the main application file.</span>
  <span class="dt">deps</span>: [<span class="st">&quot;main&quot;</span>],

  <span class="dt">paths</span>: {
    <span class="co">// JavaScript folders.</span>
    <span class="dt">libs</span>: <span class="st">&quot;../assets/js/libs&quot;</span>,
    <span class="dt">plugins</span>: <span class="st">&quot;../assets/js/plugins&quot;</span>,

    <span class="co">// Libraries.</span>
    <span class="dt">jquery</span>: <span class="st">&quot;../assets/js/libs/jquery&quot;</span>,
    <span class="dt">lodash</span>: <span class="st">&quot;../assets/js/libs/lodash&quot;</span>,
    <span class="dt">backbone</span>: <span class="st">&quot;../assets/js/libs/backbone&quot;</span>
  },

  <span class="dt">shim</span>: {
    <span class="co">// Backbone library depends on lodash and jQuery.</span>
    <span class="dt">backbone</span>: {
      <span class="dt">deps</span>: [<span class="st">&quot;lodash&quot;</span>, <span class="st">&quot;jquery&quot;</span>],
      <span class="dt">exports</span>: <span class="st">&quot;Backbone&quot;</span>
    },

    <span class="co">// Backbone.LayoutManager depends on Backbone.</span>
    <span class="st">&quot;plugins/backbone.layoutmanager&quot;</span>: [<span class="st">&quot;backbone&quot;</span>]
  }

});</code></pre>
<p>The first option defined in the above config is <code>deps: [&quot;main&quot;]</code>. This informs Require.js to load up our main.js file, which is considered the entry point for our application. You may notice that we haven't specified any other path information for <code>main</code>.</p>
<p>This is because as we haven't overridden the path to our scripts using the <code>baseUrl</code> option, Require will infer this using the path from our <code>data-main</code> attribute in index.html. In other words, our <code>baseUrl</code> is <code>app/</code> and any scripts we require will be loaded relative to this location.</p>
<p>The next block is <code>paths</code>, which we can use to specify paths relative to the <code>baseUrl</code> as well as the paths/aliases to dependencies we're likely to regularly reference.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="dt">paths</span>: {
    <span class="co">// JavaScript folders.</span>
    <span class="dt">libs</span>: <span class="st">&quot;../assets/js/libs&quot;</span>,
    <span class="dt">plugins</span>: <span class="st">&quot;../assets/js/plugins&quot;</span>,

    <span class="co">// Libraries.</span>
    <span class="dt">jquery</span>: <span class="st">&quot;../assets/js/libs/jquery&quot;</span>,
    <span class="dt">lodash</span>: <span class="st">&quot;../assets/js/libs/lodash&quot;</span>,
    <span class="dt">backbone</span>: <span class="st">&quot;../assets/js/libs/backbone&quot;</span>
  },</code></pre>
<p>Next we have the <code>shim</code> config:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="dt">shim</span>: {
    <span class="co">// Backbone library depends on lodash and jQuery.</span>
    <span class="dt">backbone</span>: {
      <span class="dt">deps</span>: [<span class="st">&quot;lodash&quot;</span>, <span class="st">&quot;jquery&quot;</span>],
      <span class="dt">exports</span>: <span class="st">&quot;Backbone&quot;</span>
    },

    <span class="co">// Backbone.LayoutManager depends on Backbone.</span>
    <span class="st">&quot;plugins/backbone.layoutmanager&quot;</span>: [<span class="st">&quot;backbone&quot;</span>]
  }</code></pre>
<p><code>shim</code> is an important part of our Require.js configuration which allows us to load libraries which are not AMD compliant. The basic idea here is that rather than requiring all libraries to implement support for AMD, the <code>shim</code> takes care of the hard work for us.</p>
<p>For example, in the block below, we state that Backbone.js is dependent on Lodash (a fork of Underscore.js) and jQuery being loaded before it. Once they've been loaded, we then use the global export <code>Backbone</code> as the module value.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="dt">backbone</span>: {
      <span class="dt">deps</span>: [<span class="st">&quot;lodash&quot;</span>, <span class="st">&quot;jquery&quot;</span>],
      <span class="dt">exports</span>: <span class="st">&quot;Backbone&quot;</span>
    }</code></pre>
<p>Finally, we inform Require.js that the Backbone <a href="https://github.com/tbranyen/backbone.layoutmanager">LayoutManager</a> plugin (a template and layout manager, also included) requires that Backbone be loaded before it should be.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="co">// Backbone.LayoutManager depends on Backbone.</span>
    <span class="st">&quot;plugins/backbone.layoutmanager&quot;</span>: [<span class="st">&quot;backbone&quot;</span>]</code></pre>
<p>This entire setup ensures that our scripts correctly get loaded in the order in which we expect.</p>
<h3 id="main.js">main.js</h3>
<p>Next, we have <code>main.js</code>, which defines the entry point for our application. We use a global <code>require()</code> method to load an array any other scripts needed, such as our application <code>app.js</code> and our main router <code>router.js</code>. Note that most of the time, we will only use <code>require()</code> for bootstrapping an application and a similar method called <code>define()</code> for all other purposes.</p>
<p>The function defined after our array of dependencies is a callback which doesn't fire until these scripts have loaded. Notice howe we're able to locally alias references to &quot;app&quot; and &quot;router&quot; as <code>app</code> and <code>Router</code> for convenience.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">require([
  <span class="co">// Application.</span>
  <span class="st">&quot;app&quot;</span>,

  <span class="co">// Main Router.</span>
  <span class="st">&quot;router&quot;</span>
],

<span class="kw">function</span>(app, Router) {

  <span class="co">// Define your master router on the application namespace and trigger all</span>
  <span class="co">// navigation from this instance.</span>
  <span class="kw">app</span>.<span class="fu">router</span> = <span class="kw">new</span> Router();

  <span class="co">// Trigger the initial route and enable HTML5 History API support, set the</span>
  <span class="co">// root folder to &#39;/&#39; by default. Change in app.js.</span>
  <span class="kw">Backbone.history</span>.<span class="fu">start</span>({ <span class="dt">pushState</span>: <span class="kw">true</span>, <span class="dt">root</span>: <span class="kw">app</span>.<span class="fu">root</span> });

  <span class="co">// All navigation that is relative should be passed through the navigate</span>
  <span class="co">// method, to be processed by the router. If the link has a `data-bypass`</span>
  <span class="co">// attribute, bypass the delegation completely.</span>
  $(<span class="kw">document</span>).<span class="fu">on</span>(<span class="st">&quot;click&quot;</span>, <span class="st">&quot;a:not([data-bypass])&quot;</span>, <span class="kw">function</span>(evt) {
    <span class="co">// Get the absolute anchor href.</span>
    <span class="kw">var</span> href = $(<span class="kw">this</span>).<span class="fu">attr</span>(<span class="st">&quot;href&quot;</span>);

    <span class="co">// If the href exists and is a hash route, run it through Backbone.</span>
    <span class="kw">if</span> (href &amp;&amp; <span class="kw">href</span>.<span class="fu">indexOf</span>(<span class="st">&quot;#&quot;</span>) === <span class="dv">0</span>) {
      <span class="co">// Stop the default event to ensure the link will not cause a page</span>
      <span class="co">// refresh.</span>
      <span class="kw">evt</span>.<span class="fu">preventDefault</span>();

      <span class="co">// `Backbone.history.navigate` is sufficient for all Routers and will</span>
      <span class="co">// trigger the correct events. The Router&#39;s internal `navigate` method</span>
      <span class="co">// calls this anyways. The fragment is sliced from the root.</span>
      <span class="kw">Backbone.history</span>.<span class="fu">navigate</span>(href, <span class="kw">true</span>);
    }
  });

});</code></pre>
<p>Inline, Backbone Boilerplate includes boilerplate code for initializing our router with HTML5 History API support and handling other navigation scenarios, so we don't have to.</p>
<h3 id="app.js">app.js</h3>
<p>Let us now look at our <code>app.js</code> module. Typically, in non-Backbone Boilerplate applications, an <code>app.js</code> file may contain the core logic or module references needed to kick start an app.</p>
<p>In this case however, this file is used to define templating and layout configuration options as well as utilities for consuming layouts. To a beginner, this might look like a lot of code to comprehend, but the good news is that for basic apps, you're unlikely to need to heavily modify this. Instead, you'll be more concerned with modules for your app, which we'll look at next.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define([

  <span class="co">// Libraries.</span>
  <span class="st">&quot;jquery&quot;</span>,
  <span class="st">&quot;lodash&quot;</span>,
  <span class="st">&quot;backbone&quot;</span>,

  <span class="co">// Plugins.</span>
  <span class="st">&quot;plugins/backbone.layoutmanager&quot;</span>

],

<span class="kw">function</span>($, _, Backbone) {

  <span class="co">// Provide a global location to place configuration settings and module</span>
  <span class="co">// creation.</span>
  <span class="kw">var</span> app = {
    <span class="co">// The root path to run the application.</span>
    <span class="dt">root</span>: <span class="st">&quot;/&quot;</span>
  };

  <span class="co">// Localize or create a new JavaScript Template object.</span>
  <span class="kw">var</span> JST = <span class="kw">window</span>.<span class="fu">JST</span> = <span class="kw">window</span>.<span class="fu">JST</span> || {};

  <span class="co">// Configure LayoutManager with Backbone Boilerplate defaults.</span>
  <span class="kw">Backbone.LayoutManager</span>.<span class="fu">configure</span>({
    <span class="dt">paths</span>: {
      <span class="dt">layout</span>: <span class="st">&quot;app/templates/layouts/&quot;</span>,
      <span class="dt">template</span>: <span class="st">&quot;app/templates/&quot;</span>
    },

    <span class="dt">fetch</span>: <span class="kw">function</span>(path) {
      path = path + <span class="st">&quot;.html&quot;</span>;

      <span class="kw">if</span> (!JST[path]) {
        $.<span class="fu">ajax</span>({ <span class="dt">url</span>: <span class="kw">app</span>.<span class="fu">root</span> + path, <span class="dt">async</span>: <span class="kw">false</span> }).<span class="fu">then</span>(<span class="kw">function</span>(contents) {
          JST[path] = <span class="kw">_</span>.<span class="fu">template</span>(contents);
        });
      }

      <span class="kw">return</span> JST[path];
    }
  });

  <span class="co">// Mix Backbone.Events, modules, and layout management into the app object.</span>
  <span class="kw">return</span> <span class="kw">_</span>.<span class="fu">extend</span>(app, {
    <span class="co">// Create a custom object with a nested Views object.</span>
    <span class="dt">module</span>: <span class="kw">function</span>(additionalProps) {
      <span class="kw">return</span> <span class="kw">_</span>.<span class="fu">extend</span>({ <span class="dt">Views</span>: {} }, additionalProps);
    },

    <span class="co">// Helper for using layouts.</span>
    <span class="dt">useLayout</span>: <span class="kw">function</span>(name) {
      <span class="co">// If already using this Layout, then don&#39;t re-inject into the DOM.</span>
      <span class="kw">if</span> (<span class="kw">this</span>.<span class="fu">layout</span> &amp;&amp; <span class="kw">this</span>.<span class="fu">layout</span>.<span class="fu">options</span>.<span class="fu">template</span> === name) {
        <span class="kw">return</span> <span class="kw">this</span>.<span class="fu">layout</span>;
      }

      <span class="co">// If a layout already exists, remove it from the DOM.</span>
      <span class="kw">if</span> (<span class="kw">this</span>.<span class="fu">layout</span>) {
        <span class="kw">this</span>.<span class="fu">layout</span>.<span class="fu">remove</span>();
      }

      <span class="co">// Create a new Layout.</span>
      <span class="kw">var</span> layout = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Layout</span>({
        <span class="dt">template</span>: name,
        <span class="dt">className</span>: <span class="st">&quot;layout &quot;</span> + name,
        <span class="dt">id</span>: <span class="st">&quot;layout&quot;</span>
      });

      <span class="co">// Insert into the DOM.</span>
      $(<span class="st">&quot;#main&quot;</span>).<span class="fu">empty</span>().<span class="fu">append</span>(<span class="kw">layout</span>.<span class="fu">el</span>);

      <span class="co">// Render the layout.</span>
      <span class="kw">layout</span>.<span class="fu">render</span>();

      <span class="co">// Cache the reference.</span>
      <span class="kw">this</span>.<span class="fu">layout</span> = layout;

      <span class="co">// Return the reference, for chainability.</span>
      <span class="kw">return</span> layout;
    }
  }, <span class="kw">Backbone</span>.<span class="fu">Events</span>);

});</code></pre>
<h3 id="creating-backbone-boilerplate-modules">Creating Backbone Boilerplate Modules</h3>
<p>Not to be confused with simply being just an AMD module, a Backbone Boilerplate <code>module</code> is a script composed of a:</p>
<ul>
<li>Model</li>
<li>Collection</li>
<li>Views (optional)</li>
</ul>
<p>We can easily create a new Boilerplate module using <code>grunt-bbb</code> once again using <code>init</code>:</p>
<pre class="shell"><code># Create a new module
bbb init:module

# Grunt prompt
Please answer the following:
[?] Module Name foo
[?] Do you need to make any changes to the above before continuing? (y/N) n

Writing app/modules/foo.js...OK

Initialized from template &quot;module&quot;.</code></pre>
<p>This will generate a module <code>foo.js</code> as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define([
  <span class="co">// Application.</span>
  <span class="st">&quot;app&quot;</span>
],

<span class="co">// Map dependencies from above array.</span>
<span class="kw">function</span>(app) {

  <span class="co">// Create a new module.</span>
  <span class="kw">var</span> Foo = <span class="kw">app</span>.<span class="fu">module</span>();

  <span class="co">// Default model.</span>
  <span class="kw">Foo</span>.<span class="fu">Model</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({

  });

  <span class="co">// Default collection.</span>
  <span class="kw">Foo</span>.<span class="fu">Collection</span> = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
    <span class="dt">model</span>: <span class="kw">Foo</span>.<span class="fu">Model</span>
  });

  <span class="co">// Return the module for AMD compliance.</span>
  <span class="kw">return</span> Foo;

});</code></pre>
<p>Notice how boilerplate code for our model and collection has already been written for us, as well as code for consuming the layout utilities defined in <code>app.js</code>.</p>
<p>Now, you may be wondering where or how Views fit into this setup. Although Backbone Boilerplate doesn't include Views in its generated modules by default, we can easily add them ourselves as needed.</p>
<p>e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define([
  <span class="co">// Application.</span>
  <span class="st">&quot;app&quot;</span>,

  <span class="co">// Views</span>
  <span class="st">&quot;modules/foo/views&quot;</span>
],

<span class="co">// Map dependencies from above array.</span>
<span class="kw">function</span>(app, Views) {

  <span class="co">// Create a new module.</span>
  <span class="kw">var</span> Foo = <span class="kw">app</span>.<span class="fu">module</span>();

  <span class="co">// Default model.</span>
  <span class="kw">Foo</span>.<span class="fu">Model</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({

  });

  <span class="co">// Default collection.</span>
  <span class="kw">Foo</span>.<span class="fu">Collection</span> = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
    <span class="dt">model</span>: <span class="kw">Foo</span>.<span class="fu">Model</span>
  });

  <span class="co">// Default views</span>
  <span class="kw">Foo</span>.<span class="fu">Views</span> = Views;

  <span class="co">// Return the module for AMD compliance.</span>
  <span class="kw">return</span> Foo;

});</code></pre>
<p>Optionally, we may also wish to include references to plugins such as the Backbone LocalStorage or Offline adapters. One clean way of including a plugin in the above boilerplate could be:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define([
  <span class="st">&quot;app&quot;</span>,

  <span class="co">// Libs</span>
  <span class="st">&quot;backbone&quot;</span>,

  <span class="co">// Plugins</span>
  <span class="st">&quot;plugins/backbone-localstorage&quot;</span>
],

<span class="kw">function</span>(app, Backbone, Views) {
  <span class="co">// Create a new module.</span>
  <span class="kw">var</span> Foo = <span class="kw">app</span>.<span class="fu">module</span>();

  <span class="co">// Default model.</span>
  <span class="kw">Foo</span>.<span class="fu">Model</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({

  });

  <span class="co">// Default collection.</span>
  <span class="kw">Foo</span>.<span class="fu">Collection</span> = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
    <span class="dt">model</span>: <span class="kw">Foo</span>.<span class="fu">Model</span>,

    <span class="co">// Save all of the items under the `&quot;foo&quot;` namespace.</span>
    <span class="dt">localStorage</span>: <span class="kw"