Top Banner
 ук о вод ст во j Q u e r y -р а з работ ч и ка OR E IL L Y  л е к с М ак к оу ПИТЕР
285

Алекс Маккоу - Веб-приложения на JavaScript - 2012.pdf

Jun 02, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/11/2019 - - JavaScript - 2012.pdf

    1/285

    jQuery-

    OREILLY

  • 8/11/2019 - - JavaScript - 2012.pdf

    2/285

    ^ '

  • 8/11/2019 - - JavaScript - 2012.pdf

    3/285

    Alex MacCaw

    JavaScriptWeb Applications

    OREILLY*

    Beijing Cambridge Farnham Koln Sebastopol Tokyo

  • 8/11/2019 - - JavaScript - 2012.pdf

    4/285

    -

    J avaScript

    ^ ' - - - -- - - -

    - -

    2012

  • 8/11/2019 - - JavaScript - 2012.pdf

    5/285

  • 8/11/2019 - - JavaScript - 2012.pdf

    6/285

    ..........................................................................................13

    1. MVC ....................................................................... 21

    2. ........................................................40

    3. ................................................................ 53

    4. .................................................. 73

    5. ...................... 91

    . ............................................... 100

    7. ............................................................. 109

    8. - ................................. 126

    9. ...................................................137

    10. ............................ ....................... .............. 164

    11. Spine.............................................................. 172

    12. Backbone........................................................198

    13. JavaScriptMVC..................................................220

    . jQuery......................................................... 245

    . CSS-......................................................257

    . CS$3............................................... 262

  • 8/11/2019 - - JavaScript - 2012.pdf

    7/285

    ........................................................................................13 ?...............................................................................13

    .............................................................................................................. 14

    , ............................................................... 17

    .............................................................................................18

    , ............................................................18

    j Query...............................................................................................................19

    Holla................................................................................................................................19 ......................................................................................................... 19

    ............................................................................................................... 20

    1. MVC ................................................................. 21 ................................................................................................................... 21

    ....................................................................................................22

    MVC?.............................................................................................................. 23

    .............................................................................................................................. 23

    ................................................................................................................. 24 ...................................................................................................................... 25

    , .................................................................. 26

    ................................................................................... 28

    .................................................... 28

    Prototype............................. 31

    ............................................ 32

    ............................................................................................................ 33

    .................................35

    ................................................................................... 37

    ........................................................................................................38

    2. .................................................40

    ............................................................................................... 40

    ..................................................................................... 41

    ...........................................................................................................42

  • 8/11/2019 - - JavaScript - 2012.pdf

    8/285

    7

    ................................................................................................................ 42

    ................................................................................................... 44

    ...................................................................................................45

    ..............................................................................................45

    .........................................................................................46 j Query............................47

    , DOM..................................................49

    3. .............................................................53MVC ......................................................................53

    ORM.................................................................................................................55

    .........................................................................................55

    ORM .......................................................................................... 56

    ..................................................................................................58 ID ..........................................................................................59

    ........................................................................................................60

    ......................................................................................................... 61

    ........................................................................... 62

    Ajax.............................................................................. 63

    JSONP.............................................................................................................................66

    ................................... 67

    ORM...................................................................................67

    .......................................................................................68

    ORM......................................70

    ............................................................................71

    4. ...............................................73

    ............................................................................................................. 74

    ..................................................................................................... 74

    ..................................................................................................... 74

    ..................................................................................................75

    .................................................................................. 76

    ................................................................. 78

    ........................................................................................... 79

    .............................................................................................. 81

    ...................................................................................................... 83

    ........................................................................................................... 85

    URL-..........................................................................85

    .................................................................................. 86

    Ajax Crawling.................................................................................................................87 History API HTML5.........................................................................88

  • 8/11/2019 - - JavaScript - 2012.pdf

    9/285

    8

    5. ............... 91 .......................................................91

    ...........................................................................................................................93

    .................................................................................................95 .....................................................................................................95

    ....................................................................................................................97

    ........................................................................................................98

    6. ....................................... 100

    CommonJS....................................................................................................................... 101

    ....................................................................................................... 102

    ....................................................................................................... 102

    ...................................................................................................103Yabble............................................................................................................................103

    RequireJS...................................................................................................................... 104

    .............................................................................................. 106

    ............................................................................. ................107

    LABjs.............................................................................................................................107

    FUBC............................................................................................................................108

    7. ........................................................109

    ..................................................................................................109 ...............................................................................110

    ....................................................................................................................110

    ......................................................... .....................................................111

    ............................................................................................112

    ..................................................................... 114

    ......................................... 115

    ..................................................................................................115

    ............

    ....................................................................................................116 ...................................................................................... 116

    ................................................................................................................ 117

    .............................................................................................................. 119

    ..................................................................................120

    .......................................................................:.................................. 120

    Ajax..................................................................122

    j Query............124

    ............................ 124

    ........................................................................................................... 125

  • 8/11/2019 - - JavaScript - 2012.pdf

    10/285

    9

    8. - ........................126

    ..........................................................126

    WebSockets..................................................................................................................... 127

    Node.js Socket.IO...................................................................................................... 131 ................................................................................. 133

    .................................................................................................... 135

    9. ................................................137

    ...................................................................................................139

    ............................................................................................................... 139

    QUnit.............................................................................................................................140

    Jasmine..........................................................................................................................144

    .........................................................................................................................146 ............................................................................................ 149

    Zombie...........................................................................................................................149

    Ichabod....................................................................................................... ...................151

    ..................................................................................... 152

    ..........................................................................................153

    .................................................................................................................... 153

    -............................................................................................................. 154

    Firebug..........................................................................................................................155

    ............................................................................................................................156 ....................................................!................ 157

    ............................................................................................ 158

    ..............................................................................................160

    ................................................................................161

    10. ..........................................................164 ..................................................................................................... 164

    ............................................................................................................... 165

    ............................................................................................................. 167 Gzip............................................................................................ 169

    CDN...................................................................................................169

    .........................................................................................................................170

    ............................................................................................................................171

    11. Spine.......................................................172 ........................................................................................................................ 172

    ......................... ....................................................................................................173

    ..................................................................................................173

  • 8/11/2019 - - JavaScript - 2012.pdf

    11/285

    1 0

    ..................................................................................................174

    ...................................................................................................................... 175

    .......................................................................................................................... 176 ............................................................................................. ;............................ 177

    ...................................................................................................178

    ....................................................................................................... 179 ..................................................................................................................... 180

    .............................................................................................. 180

    ..................................................................................................................183

    ..........................................................................184

    .................................................................................................................... 184

    ............................................................................................185

    ............................................................................................... 185

    ..................................................................................................186

    ..................................................................................................186

    ...........................................................................................................187

    .........................................................189

    Contact..........................................................................................................190

    Sidebar....................................................................................................191

    Contacts................................................................................................193

    ..........................................................................................................196

    12. Backbone.................................................198 ............................................................................................................................199

    ...................................................................................................200

    ...................................................................................................................... 201

    ............202

    ...............................................................................................................203

    ................................................................................. 204

    ...........................................................................................204

    ................................................................................................. 205

    ................................................................................................................. 206 ......................................................................................... 208

    .............................................................................................210

    .............................................................................................. 210

    ........................................................... .................................... 211

    ToDo ( ).....................................................................213

    13. JavaScriptMVC.........................................220 .......................................................................................................................221

    ............................................................................................................................ 221 ................................................................................................ 222

    ......................................................................................... 222

  • 8/11/2019 - - JavaScript - 2012.pdf

    12/285

    11

    .................................................................................................... 222

    .......................................................................................223

    .................................... ...................................................................223

    ...........................................................................................................223

    .............................................................................................................................224 .........................................................................224

    ................................................................................................227

    ............................................................................................... 227

    ...................................................................................................................228

    ..................................................................................................228

    ................................................................................................229

    ........................................................................................................230

    ...................................................................................................... 231

    .........................................................................................................231 .....................................................................................................231

    .........................................................................................................232

    .............................................................................................. 232

    CRUD- ..........................................................................................................233

    ...........................233

    ...............................................................................................234

    j Query..............................................................................................234

    script-...............................................................................................235S.View ................................................................................................235

    Deferred- .......................................................................................................235

    , .............................236

    S.Controller: j Query .................................................................................................... 237

    ................................................................................................239

    ........................................................................ 240

    ..................................................................................................... 241

    ................................................................................................241 : CRUD-.......................................243

    . jQuery................................................... 245

    DOM- ................................................................................. 247

    DOM................................................................................................................248

    ..........................................................................................................................250

    Ajax............................................................................................................................... ...251

    ......................................................252

    ................................................................................................................... 253

    jQuery Growl................................................... 254

  • 8/11/2019 - - JavaScript - 2012.pdf

    13/285

    12

    . CSS-...............................................257 ....................................................................................................................257

    ......................................................................................................................... 258

    .......................................................................................................258

    .............................................................................. 259

    ................................................................................................................................259

    Less?...............................................................................259

    ....................................................................... 260

    Rack........................................................................................... 260

    JavaScript................................................................................................260Less.app.........................................................................................................................260

    . CSS3......................................... 262

    ........................................................................................................................263

    ................................................................................................................................263

    ......................................................................................................... 264

    .....................................................................................................265

    ..............................................................................................................266

    ........................................................................................................................267 ................................................................................................................268

    .......................................................................................................................268

    N- ................................................................................................269

    .............................................................' ......................................... 269

    ..............................................................................................270

    .........................................................................................................................270

    ................................................................271

    ...................................272

    ............................................................................................................. 272 ......................................................................273

    ...........................................................................................................................274

    ...............................................................................................275

    Modemizr..................................................................................................................... 276

    Google Chrome Frame.......................................................................... 277

    .............................................................................................................278

  • 8/11/2019 - - JavaScript - 2012.pdf

    14/285

    1995 JavaScript Netscape J IT. - , Ajax , JavaScript .

    JavaScript , , -

    . - . JavaScript - , , .

    JavaScript: CSS3 HTML5, , - , Safari, Chrome, Firefox , , IE9. - , , - . HTML5 CSS3 - , , , .

    . . , -, , . -

    . , JavaScript .

    ? JavaScript, , JavaScript: ( ,2012).

  • 8/11/2019 - - JavaScript - 2012.pdf

    15/285

    14

    JavaScript, , jQuery , JavaScript . , , , - JavaScript.

    1

    JavaScript , -. MVC, JavaScript , - .

    2

    , , API . jQuery, . - , DOM , - PubSub.

    3

    MVC , .

    MVC , - ORM . JSONP Ajax. , HTML5 , - RESTful.

    4

    - .

    - , - , DOM. , , URL, , API HTML5. .

    5

    JavaScript. -

    , ( , sc r ip t -

  • 8/11/2019 - - JavaScript - 2012.pdf

    16/285

    15

    ). .

    6

    JavaScript CommonJS. , CommonJS, CommonJS -, Yabble RequireJS. - , - . , CommonJS, Sprockets LABjs.

    7

    , HTML5: API . , , , , - . - () . XMLHttpRequest Level , , - j Query Ajax API.

    8

    - WebSockets. - . WebSockets , - API JavaScript. RPC, WebSockets . - Socket. I -

    . 9

    , JavaScript. - , , , , QUnit Jasmine. , Selenium.

    , Firefox WebKit, JavaScript.

  • 8/11/2019 - - JavaScript - 2012.pdf

    17/285

    16

    10

    , JavaScript: . - -

    , , gzip , . (CDN) - - , .

    11

    JavaScript, . Spine VC , , . - : , , . , -, , .

    12

    - Backbone, JavaScript . Backbone, ,, . - RESTful JSON Backbone . , .

    13

    JavaScriptMVC, , j Query - JavaScript. JavaScriptMVC, , ,

    -. , CRUD, , , JavaScriptMVC.

    j Query, -, . j Query -, .

    API, DOM, DOM, , .

  • 8/11/2019 - - JavaScript - 2012.pdf

    18/285

    , 17

    jQuery Ajax API, GET POST JSON. jQuery - . : jQuery Growl.

    Less, CSS, , , - . Less - CSS, - CSSS. , Less, - JavaScript Less CSS.

    CSS3. - CSS3, , - . CSS3 , rgba-, , , . - Modernizr box-sizing.

    , , :

    .

    URL, , , - .

    , - , , , , , , , , , , , , , , -, , , , , , XML,HTML, , .

    , , - , , .

  • 8/11/2019 - - JavaScript - 2012.pdf

    19/285

    18

    GitHub ( https://github.com/maccman/book-assets).

    zip( https://glthub.com/maccman/book-assets/zipball/master)

    - . . , , - .

    assets/_/ .

    ,

    - assert() assertEqual(). assert () ( ) , - true; -, . - assert() : . true, :

    var assert = function(value, msg) {if ( lvalue )throw(msg || (value + " true));

    }; assertEqual() , - . - , assert () , . , :

    var assertEqual = function(vall, val2, msg) {if (vail !== val2)throw(msg || (vail + " " + val2));

    };

    , , . , :

    assert( true );

    // assertEqual()assert( false === false )j

    assertEqual( 1, 1 );

    asser tEqual(), , , ,

    https://github.com/https://glthub.com/maccman/book-assets/zipball/masterhttps://glthub.com/maccman/book-assets/zipball/masterhttps://github.com/
  • 8/11/2019 - - JavaScript - 2012.pdf

    20/285

    jQuery 19

    . , - assets/chOO/deep_equality.html.

    jQuery jQuery, - JavaScript, , DOM, Ajax. -, , , jQuery JavaScript, .

    jQuery, -

    . API, - DOM. jQuery .

    Holla , Holla , JavaScript. Holla , - , . , Holla , :

    CSS3 HTML5 ; ;

    Sprockets Less;

    WebSockets ;

    JavaScript , .

    Holla GitHub (http://github.com/maccman/holla) . Holla (. . 0.1).

    , . - , - . , - , , .

    . (Stuart Eccles), (Tim Malbon),

    http://github.com/http://github.com/
  • 8/11/2019 - - JavaScript - 2012.pdf

    21/285

    20 .

    Holla

    | *, [ ) ( + ' ttp /local host 3000/ria Coogle

    Holla # CD

    Share

    . 0.1. Holla, -

    (Ben Griffins) (Sean OHalpin),

    ; (James Adam), (Paul Battley) (Jonah Fox) - .

    , : (Henrik Joreteg), (Justin Meyer), (Lea Verou), (Addy Osmani), - (Alex Barbara), (Max Williams) (JulioCesar Ody).

    , , .

    , , - [email protected]( , ).

    !

    , , GitHub(https://github.com/maccman/bookassets).

    http://www.piter.com - .

    mailto:[email protected]://github.com/maccman/book-assetshttp://www.piter.com/http://www.piter.com/https://github.com/maccman/book-assetsmailto:[email protected]
  • 8/11/2019 - - JavaScript - 2012.pdf

    22/285

    MVC

    JavaScript - . , Netscape , Google V8. , ECMAScript. - .

    JavaScript, - . , , , -

    , , . JavaScript?

    , JavaScript, , Java Java, - . , , . , - Python Ruby, - , . JavaScript .

    JavaScript , - , , , , -. , , - , , . JavaScript .

    JavaScript , JavaScript

  • 8/11/2019 - - JavaScript - 2012.pdf

    23/285

    22 1. MVC

    , . , Gmail Google Maps, - , . JavaScript . JavaScript

    , , - , , .

    , JavaScript . , , . , JavaScript, . , (Model View Controller, MVC), HTML JavaScript.

    JavaScript , , (Douglas Crockford) JavaScript: The Good Parts (- OReilly). , JavaScript , - .

    JavaScript - , , . , , , - JavaScript , HTML. , .

    , . JavaScript . , -, , - , Python Ruby. , , ?

    , MVC, , -

    . , JavaScript .

  • 8/11/2019 - - JavaScript - 2012.pdf

    24/285

    MVC? 23

    MVC?MVC , : - (Model, ), (View, )

    (Controller, ). , - .

    1. .

    2. .

    3. , .

    4. .

    , , . 1.1 , Holla.

    Holla 3 CD

    Profile

    Activity

    Settings

    Hello there!

    V. ___________ J Share

    . 1.1. - Holla

    1. .

    2. .

    3. Chat Model.

    4. .

    5. ^.

    MVC - . MVC - , .

    , . MVC .

    , . -, User, , - , .

    . - , .

  • 8/11/2019 - - JavaScript - 2012.pdf

    25/285

  • 8/11/2019 - - JavaScript - 2012.pdf

    26/285

    25

    : , - , .

    , , ,

    :// template.htmlfunction formatDate(date) {

    / * . . . * /};

    ${ formatDate(this.date) }

    formatDate() , MVC, - , . - , , , , MVC .

    // helper.jsvar helper = {};helper.formatDate = function(){ /* ... */ };// template.html

    ${ helper.formatDate(this.date) }

    helper, - .

    , - 5. - MVC.

    . , , - ( , ) . - . , ,

    .

  • 8/11/2019 - - JavaScript - 2012.pdf

    27/285

    26 1. MVC

    - . , jQuery:

    var Controller = {};//

    (Controller.users = function($){var nameClick = function(){

    / * . . . * />;// $(function(){$("#view .name").click(nameClick);

    ;>)(jQuery);

    users,

    Controller. , - . .

    , . MVC . 4.

    , MVC, , JavaScript. .

    JavaScript , , . , JavaScript , , .

    . JavaScript , , , JavaScript , , , . jQuery, -, . JavaScript , -, . . . , , , , JavaScript , .

    JavaScript new.

  • 8/11/2019 - - JavaScript - 2012.pdf

    28/285

    , 27

    . - JavaScript. new.

    new , return.

    , new - :

    var Person - function(name) {this.name = name;

    };// Personvar alice =^new Person('alice');// assert( alice instanceof Person );

    , -, , . , new.

    // !Person('bob'); //=> undefined ( )

    undefined, ( ), name. , new.

    new, () , - . , th is - . , , .

    , , th is . - , , , , :

    var Class = function(){var klass = function(){this.init.apply(this, arguments);

    };klass.prototype.init = function(){};return klass;

    };var Person = new Class;Person.prototype.init = function(){// Person

    >;

    // :var person = new Person;

  • 8/11/2019 - - JavaScript - 2012.pdf

    29/285

    28 1. MVC

    : JavaScript 2, class . - class _class

    klass.

    JavaScript:

    Person.find = function(id){ /*...*/ };var person = Person.find(l);

    - prototype:

    Person.prototype.breath = function(){ /*...*/ };var person = new Person;person.breath();

    fn:

    Person.fn = Person.prototype;Person.fn.run = function(){ /*...*/ };

    jQuery, jQuery, jQuery .f n.

    - . , -

    . , , - :

    var Person = new Class;

    // , . Person.find = function(id){ /* ... *1 };

    // var person = Person.find(l);

  • 8/11/2019 - - JavaScript - 2012.pdf

    30/285

    29

    , , - :

    var Person = new Class;

    // , Person.prototype.save = function(){ /* ... */ };

    // var person = new Person;person.save();

    , . , .

    - : extend() include():

    var Class = function(){var klass = function(){this.init.apply(this, arguments);

    };

    klass.prototype.init = function(){};

    // klass.fn = klass.prototype;

    // klass.fn.parent = klass;

    // klass.extend = function(obj){var extended = obj.extended;for(var i in obj){klassfi] = obj[i];

    >if (extended) extended(klass)

    };

    // klass.include = function(obj){var included = obj.included;for(var i in obj){klass.fn[i] = obj[i];

    >if (included) included(klass)

    };

    return klass;>;

  • 8/11/2019 - - JavaScript - 2012.pdf

    31/285

    30 1. MVC

    - extend() , . :

    var Person = new Class;Person.extend({find: function(id) { /* ... */ },exists: functions(id) { /* ... */ }

    });var person = Person.find(l);

    inc lude () , , , . , ,

    .var Person = new Class;Person.include({save: function(id) { /* ... */},destroy: functions(id) { /* ... */ }

    });var person = new Person;person.save();

    (extended) -

    (included). , :

    Person.extend({extended: function(klass) {console.log(klass, " !");

    }});

    Ruby, -. , -. , - .

    var ORMModule = {save: function(){//

    }};var Person = new Class;var Asset = new Class;Person.include(ORMModule);Asset.include(ORMModule);

  • 8/11/2019 - - JavaScript - 2012.pdf

    32/285

    31

    Prototype

    prototype,

    . , - .

    JavaScript , , - , . . - : , , . - , .

    . JavaScript -. , JavaScript - , Object .prototype. , , , undefined ( ).

    , Array.prototype, JavaScript.

    , -

    . . :

    var Animal = function(){};

    Animal.prototype.breath = function(){console.log('');

    };

    var Dog = function(){};

    // Dog () Animal ()Dog.prototype = new Animal;Dog.prototype.wag = function(){console.log(' ');

    };

    :

    var dog = new Dog;dog.wag();

    dog.breath(); //

  • 8/11/2019 - - JavaScript - 2012.pdf

    33/285

    32 1. MVC

    . (parent):

    var Class = function(parent){var klass = function(){this.init.apply(this, arguments);

    };

    // klassif (parent) {var subclass = function() { };subclass.prototype = parent.prototype;klass.prototype = new subclass;

    >;

    klass.prototype.init = function(){};

    // klass.fn = klass.prototype;klass.fn.parent = klass;klass._super = klass._proto__;

    /* (include) (extend)... */

    return klass;

    };

    Class parent, - . - . , - , .

    _

    proto__;. , Super, js, , -.

    , Class:

    var Animal = new Class;

    Animal.include({breath: function(){

    console.log('');}

  • 8/11/2019 - - JavaScript - 2012.pdf

    34/285

    });

    var Cat = new Class(Animal)

    // var tommy = new Cat;

    tommy.breath();

    JavaScript, . , - , . , . . - th is , , .

    , : apply() 11(). , -.

    apply() : . , . :

    function.apply(this, [1, 23 3])

    call() , . , - . , - , apply() , .

    function.call(this, 1, 2, 3);

    ? , . JavaScript - , - . ( , . , , .)

    j Query apply() call () API, - each(). , , - , :

    $(*.clicky1).click(function(){// 'this* $(this).hide();

    });$(' ').each(function(){// 'this' $(this).remove();

    ;

  • 8/11/2019 - - JavaScript - 2012.pdf

    35/285

    34 1. MVC

    - th is . :

    var clicky * {wasClicked: function(){

    / * . . . * /

    addListeners: function(){var self * this;$('.clicky').click(function(){self.wasClicked()

    });}

    >;

    clicky.addListeners(); , apply, - , :

    var proxy = function(func, thisObject){return(function(){return func.apply(thisObject, arguments);

    ;};

    var clicky = {

    wasClicked: function(){/ * . . . * /

    b

    addListeners: function(){var self = this;$('.clicky').click(proxy(this.wasClicked, this));

    }};

    , click; jQuery, , . API jQuery , ( , , , jQuery. proxy()):

    $('.clicky').click($.proxy(function(){ /* ... */ }, this));

    1() 11() . :

    var {

    log: function(){if (typeof console == "undefined") return;

  • 8/11/2019 - - JavaScript - 2012.pdf

    36/285

    35

    // var args * jQuery.makeArray(arguments);

    // args.unshift("(App)");

    // console.log.apply(console, args);

    >};

    , , , , conso le .lo g(). arguments, -, ,

    . , -, j query.makeArray().

    , , - , . -

    , , , - . .:

    var Class = function(parent){var klass = function(){

    th is .i n i t. apply(this, arguments);};kla ss.p roto typ e.in it = function(){};kla ss.fn = klass .prototype;

    // -klass.proxy = function(func){

    var self = th is;return(function(){

    return func.apply(self, arguments);});

    }

    // kla ss.fn.proxy = klass.proxy;

    return klass;};

  • 8/11/2019 - - JavaScript - 2012.pdf

    37/285

    36 1. MVC

    proxy () , :

    var Button = new Class;

    Button.include({init: function(element){this.element = jQuery(element);

    // (click)this.element.click(this.proxy(this.click));

    h

    click: function(){ /* .. . * /}

    ;

    click() , this.element, Button, - . JavaScript ECMAScript, (ES5) - bind(). , - this. :

    Button.include({init: function(element){this.element = jQuery(element);

    // clickthis.element.click(this.click.bind(this));

    L

    click: function(){ /* .. . * /}

    });

    () - click() . -

    bind(),

    . - , - ES5 , - . , , bind (), :

    if ( !Function.prototype.bind ) {Function.prototype.bind = function( obj ) {var slice = [].slice,

    args = slice.call(argumentsi 1),

    self = this,nop = function () {},

  • 8/11/2019 - - JavaScript - 2012.pdf

    38/285

    37

    bound function () {return self.apply( this instanceof nop ? this : ( obj || {}),

    args.concat( slice.call(arguments) ) );

    };

    nop.prototype = self.prototype;

    bound.prototype = new nop();

    return bound;

    };}

    Function prototype , - : -

    . (shimming) , , - JavaScript. es5-shim, - , ES5.

    , , . -

    . (_). -, API. , .

    JavaScript , , , - . , ,

    JavaScript:var Person = function(){};

    (function(){/

    var findByld = function(){ /* ... */ };

    Person.find = function(id){if (typeof id == "integer")return findByld(id);

    };})();

  • 8/11/2019 - - JavaScript - 2012.pdf

    39/285

    38 1. MVC

    , (findByld), -

    . Person -, .

    var, - . - , , :

    (function(exports){var foo = "bar";

    // exports.foo = foo;

    })(window);assertEqual(foo, "bar"); 7

    , - , , . jQuery ,

    HJS. , $. Class.create:

    var Person = $.Class.create({// initialize: function(name) {this.name = name;

    }});

    :

    var Student = $.Class.create(Personi {price: function() { /* ... */ }

    });var alex = new Student("Alex");alex.pay();

    :

    Person.find = function(id){ /* ... */ };

  • 8/11/2019 - - JavaScript - 2012.pdf

    40/285

    39

    API HJS , clone() equal():

    var alex = new Student("Alex");var bill = alex.clone();assert( alex.equal(bill) );

    Ho HJS Spine. - spine.js:

    var Person = Spine.Class.create();

    Person.extend({find: function() { /* ... */ }

    });

    Person.include({init: function(atts){this.attributes = atts || {};

    }});var person = Person.init();

    Spine API, , . -

    extend(), include(). , - Spine.Class.

    jQuery, Prototype. API , - .

    jQuery (John Resig) - (classical inheritance with

    the library). , , JavaScript.

    http://maccman.github.com/spine/spine.jshttp://maccman.github.com/spine/spine.js
  • 8/11/2019 - - JavaScript - 2012.pdf

    41/285

    JavaScript , - . JavaScript. Netscape Microsoft , - . W3C, Internet Explorer IE9.

    , , jQuery Prototype, - , API, . , , - , W3C.

    , addEventListener () : ( , click), , . . - () , useCapture ( - ). , DOM , , - , :

    var button = document.getElementById("createButton");

    button.addEventListener("click", function(){ /* ... */ }, false);

    , removeEventListener() , - addEventListener(). , :

    var div = document.getElementByld("div");

    var listener = function(event) { /* ... */ };div.addEventListener("click", listener, false);div.removeEventListener("click", listener, false);

  • 8/11/2019 - - JavaScript - 2012.pdf

    42/285

    41

    (listener) (event), - , , . - -

    . , , :

    click ( )

    dblclick ( )

    mousemove ( )

    mouseover ( )

    mouseout ( )

    focus ( )

    blu r ( )

    change ( , )

    submit ( )

    Quirksmode.

    , . , - ? , , , Netscape Microsoft .

    Netscape 4 , - , , . . .

    Microsoft , -

    , ,. . .

    , , , - , . W3C - . , W3C, , , .

    - , useCapture

    addEventListener(). , addEventListener(), true,

  • 8/11/2019 - - JavaScript - 2012.pdf

    43/285

    42 2.

    , false, :

    // false

    button.addEventListener("click", function(){ /*...*/}, false); , , . , addEventListener() - false.

    , stopPropagation(), . - ,

    :

    button.addEventListener("click", function(e){e.stopPropagation();

    / * . . . * /b fa lse );

    , , jQuery, stoplmmedi-atePropagation(), -, .

    . ,

    , , - . . - - . preventDefault(), . false:

    form.addEventListener("submit", function(e){/ * . . . * /

    return confirm("Bbi ?");b false);

    confirm() fals e, . . , , - , fa ls e, .

    stopPropagation() preventDefault(),

    . , -

  • 8/11/2019 - - JavaScript - 2012.pdf

    44/285

    43

    W3C, , .

    :

    bubbles

    , DOM( )

    , :

    button

    , , ( ) ( )

    ctrlKey

    , , Ctrl

    altKey

    , , Alt

    shiftKey

    , , Shift

    metaKey

    , , Meta

    , :isChar

    , ,

    charCode

    ( keypress)

    keyCode

    which

    ,

    , :

    pageXypageY

    (. . )

    screenXt screenY

  • 8/11/2019 - - JavaScript - 2012.pdf

    45/285

    44 2.

    , :

    currentTarget

    DOM

    target, originalTarget

    DOM

    relatedTarget

    DOM , ( )

    , W3C, . , , jQuery Prototype, - .

    , , - JavaScript, . , API - jQuery, , Prototype, MooTools YUI. - API, .

    API jQuery bind(). jQuery, :

    jQuery("#element").bind(eventName, handler);

    , :

    jQuery("#element").bind("click", function(event) {/ / . . .

    });

    jQuery , (click), - (submit) (mouseover).

    :$("#myDiv").click(function(){

    / / . . .});

    , , . . , - . (load) :

    jQuery(window).bind("load", function() {

    $("#signinForm").submit(checkForm);});

  • 8/11/2019 - - JavaScript - 2012.pdf

    46/285

    45

    , DOM DOMContentLoaded. DOM, . , ,

    . DOMContent Loaded , jQuery ready(), - :

    jQuery.ready(function($){$("#myForm").bind("submit", function(){ /* ... */ });

    });

    ready() - jQuery:

    jQuery(function($){// ,

    });

    , , . - addEventListener() - : :

    new function(){this.appName = "wem";document.body.addEventListener("click", function(e){// , appName alert(this.appName);

    }, false);

    >;

    - , . 1,

    . , jQuery proxy (), , :

    $("signinForm").submit($.proxy(function(){ /* ... */ }, this));

    , , - - .

  • 8/11/2019 - - JavaScript - 2012.pdf

    47/285

    46 2.

    , SproutCore, :

    // ul

    list.addEventListener("click", function(e){if (e.currentTarget.tagName == "li") {

    / * . . . * /return false;

    }}, false);

    jQuery : - d elegate () , . - c lick li . , delegate(), , :

    // ! 'li' ( )$("ul li").click(function(){ /* ... */ });

    // $("ul").delegate("li", "click", /* ... */);

    , , - , . l i , , click.

    , , . , - , jQuery. W3C, , , -

    , jQuery Prototype.

    jQuery , t r ig -ger (). , . :

    // $(".class").bind("refresh.widget", function(){});

    //

    $(".lass").trigger("refresh,widget");

  • 8/11/2019 - - JavaScript - 2012.pdf

    48/285

    47

    t rigger(). - :

    $(".class").bind("frob.widget", function(event, dataNumber){console.log(dataNumber);

    });

    $(".class").trigger("frob.widget", 5);

    , DOM.

    jQuery , jQuery, , DOM. - jQuery, , jQuery.

    - , - . .

    , jQuery . ul, - (c lick). , active, active - :

    UsersGroups

    ... ...

    , div tabsContent, - . - active div, ,

    .

  • 8/11/2019 - - JavaScript - 2012.pdf

    49/285

    48 2.

    CSS, - active:

    jQuery.fn.tabs = function(control){var element = $(this);

    control = $(control);

    element.find("li").bind("click", function(){// active

    element.find("li").removeClass("active");$(this).addClass("active");

    // active tabContent var tabName = $(this).attr("data-tab");

    control.find(">[data-tab]").removeClass("active");control.find(">[data-tab='" + tabName + "']").addClass("active");

    });

    // element.find("li:first").addClass("active");

    // 'this' return this;

    >;

    prototype jQuery, jQuery:

    $("ul#tabs").tabs("#tabContent");

    ? - , . delegate(). , , . , , , , -.

    , , - . change.tabs , active :

    jQuery.fn.tabs = function(control){var element = $(this);control = $(control);

    element.delegate("li", "click", function(){

    // var tabName = $(this).attr("data-tab");

  • 8/11/2019 - - JavaScript - 2012.pdf

    50/285

    , DOM 49

    // element.trigger("change.tabs", tabName);

    });

    // element.bind("change.tabs", function(e, tabName){element.find("li").removeClass("active");element.find(">[data-tab='" + tabName + "']").addClass("active");

    });

    element.bind("change.tabs", function(e, tabName){control.find(">[data-tab]").removeClass("active");control.find(">[data-tab=" + tabName + "']").addClass("active");

    });

    // var firstName = element.find("li:first").attr("data-tab");element.trigger("change.tabs", firstName);return this;

    >;

    , ? , , - , -. , change.tabs :

    $("#tabs").trigger("change.tabs", "users");

    , :

    $("#tabs").bind("change.tabs", function(e, tabName){window.location.hash = tabName;

    });$(window).bind("hashchange", function(){var tabName = window.location.hash.slice(l);

    $("#tabs").trigger("change.tabs", tabName);});

    .

    , DOM

    , , , , -

  • 8/11/2019 - - JavaScript - 2012.pdf

    51/285

    50 2.

    . - (DOM), . - - , .

    (Publish/Subscribe, Pub/Sub) - , : . - , , . , , . , .

    - ,

    . , Pub/Sub ? , , . PubSub, - :

    var PubSub = {subscribe: function(ev; callback) {// _callbacks, var calls = this._callbacks || (this._callbacks = {});

    // , // , (this._callbacks[ev] || (this._callbacks[ev] = [])).push(callback);return this;

    publish: function() {// var args = Array.prototype.slice.call(arguments, 0);

    // ( )var ev = args.shift();

    // , _callbacks // var list, calls, i, 1;if (!(calls = this._callbacks)) return this;if (!(list = this._callbacks[ev])) return this;

    // for (i * 0, 1 = list.length; i < 1; i++)

    list[i].apply(this, args);return this;

  • 8/11/2019 - - JavaScript - 2012.pdf

    52/285

    , DOM 51

    >>;

    // PubSub.subscribe("wem", function(){

    alert("Wem!");5PubSub.publish("wem");

    , -, (:).

    PubSub.subscribe("user:create", function(){ /* ... */ });

    jQuery, , (Ben Alman). , - :

    /*!* jQuery Tiny Pub/Sub - V0.3 - 11/4/2010* http://benalman.com/*

    * Copyright () 2010 "Cowboy" Ben Alman* Dual licensed under the MIT and GPL licenses.* http://benalman.com/about/license/*/

    (function($){

    var = $({});

    $.subscribe = function() {o.bind.apply( o, arguments );

    };

    $.unsubscribe = function() {o.unbind.apply( o, arguments );

    };

    $.publish = function() {

    o.trigger.apply( o, arguments );>;

    })(jQuery);

    API , jQuery bind() trigger(). , - jQuery publish() subscribe():

    $.subscribe( "/some/topic", function( event, a, b, ) {console.log( event.type, a + b + );

    >);

    $.publish( "/some/topic", "a", "b", "c" );

    http://benalman.com/http://benalman.com/about/license/http://benalman.com/about/license/http://benalman.com/
  • 8/11/2019 - - JavaScript - 2012.pdf

    53/285

    52 2.

    Pub/Sub , . PubSub :

    var Asset = {};

    // PubSubjQuery.extend(Asset, PubSub);

    // publish subscribeAsset.subscribe("create", function(){

    / / . . .>);

    Asset , PubSub, extend(), jQuery. publish() subscribe() Asset. -

    , (ORM), ( ) Ajax3anpoca.

  • 8/11/2019 - - JavaScript - 2012.pdf

    54/285

    - . , - . JavaScript -. , - . - .

    , . , - , . ,

    . , . , , - . -.

    MVC , - - . MVC, ( MVC). . , , .

  • 8/11/2019 - - JavaScript - 2012.pdf

    55/285

    54 3.

    JavaScript , - . :

    var User = {records: [/*...*/]

    >;

    - User. records. , , - User. , f etchRemote() :

    var User = {records: [],fetchRemote: function(){ / *. ..* /}

    >;

    MVC. (- ) .

    , , . , destroy() - . , ,

    User:var user = new User;user.destroy()

    , User , -:

    var User = function(atts){this.attributes = atts || {};

    };User.prototype.destroy = function(){

    / * . . . * /};

    , , - , User:

    User.fetchRemote = function(){

    /* . . . */};

    , (Peter Michaux), .

  • 8/11/2019 - - JavaScript - 2012.pdf

    56/285

    ORM 55

    ORM (ORM) , JavaScript. -

    , JavaScript . ORM, , , - , -, Ajax . HTML , , . , ORM.

    ORM , . ORM SQL, ORM -

    JavaScript. , - - . , , , - , - .

    ORM Object.create(), 1 , - . - new , .

    Object. create() , , - . , , , .

    Object. create() ECMAScript, ,

    , IE, . - , :

    if (typeof Object.create !== "function")Object.create = function(o) {function F() {>F.prototype = o;return new F();

    };

    (Douglas

    Crockford) Prototypal Inheritance. , JavaScript.

  • 8/11/2019 - - JavaScript - 2012.pdf

    57/285

    56 3.

    Model, :

    var Model = {inherited: function(){}>created: function(){},

    prototype: {init: function(){}

    b

    create: function(){var object = Object.create(this);object.parent = this;object.prototype = object.fn = Object.create(this.prototype);

    object.created();this.inherited(object);return object;

    b

    init: function(){var instance = Object.create(this.prototype);instance.parent = this;instance.init.apply(instance, arguments);return instance;

    }>;

    Object.reate(), - , . create() - , Model, . init() , - Model. prototype, . . Model:

    var Asset = Model.create();var User = Model.create();

    var user = User.initQ;

    ORM, Model, :

    // jQuery.extend(Model, {find: function(){}

    ;

  • 8/11/2019 - - JavaScript - 2012.pdf

    58/285

    ORM 57

    // jQuery.extend(Model.prototype, {init: function(atts) {if (atts) this.load(atts);

    b

    load: function(attributes){for(var name in attributes)this[name] - attributes[name];

    > ;

    jQuery. extend() - for , , load(). :

    assertEqual( typeof Asset.find, "function" );

    , - extend() include() Model:

    var Model = {/* ... ... */

    extend: function(o){var extended = o.extended;jQuery.extend(this, o);

    if (extended) extended(this);b

    include: function(o){var included = o.included;jQuery.extend(this-prototype, o);if (included) included(this);

    >};

    //

    Model.extend({find: function(){}

    ;

    // Model.include({init: function(atts) { /* ... */ },load: function(attributes){ / * .. .*/}

    ;

    (assets) :

    var asset = Asset.init({name: "foo.png"});

  • 8/11/2019 - - JavaScript - 2012.pdf

    59/285

    58 3.

    , . . , .

    records, Model. , :

    // Model.records - {};

    Model.include({newRecord: true,

    create: function(){

    this.newRecord = false;this.parent.records[this.id] = this;

    b

    destroy: function(){delete this.parent.records[this.id];

    > ;

    ? , :

    Model.include({update: function(){this.parent.records[this.id] = this;

    >>);

    , - , :

    // Model.include({

    save: function(){this.newRecord ? this.create() : this.update();

    } ;

    find(), ID?

    Model.extend({// no ID find: function(id){

    return this.records[id] || throw(" ");

    >});

  • 8/11/2019 - - JavaScript - 2012.pdf

    60/285

    ORM 59

    , ORM, :

    var asset = Asset.init();

    asset.name = "same, same";asset.id = 1asset.save();

    var asset2 = Asset.init();asset2.name = "but different";asset2.id = 2;asset2.save();

    assertEqual( Asset.find(l).name, "same, same" );

    asset2.destroy();

    ID ID . , , , . - GUID (Globally Unique Identifier ). , JavaScript - 128 GUID

    API, . GUID - , , , BIOS, - , - , - ! JavaScript Math. random().

    (Robert Kieffer) GUID

    , Math. random() GUID . , :

    Math.guid = function(){return '--4--'.replace(/[xy]/g,

    function(c) {var r = Math.random()*16|0, v = == 'x' ? r : (r&0x3|0x8);return v.toString(16);

    }).toUpperCase();

    >;

  • 8/11/2019 - - JavaScript - 2012.pdf

    61/285

    60 3.

    , GUID , - ORM . create():

    Model.extend({

    create: function(){if :( !this.id ) this.id = Math.guid();this.newRecord = false;this.parent.records[this.id] = this;

    }});

    ID GUID :

    var asset = Asset.init();asset.save();asset.id //=> "54E52592-313E-4F8B-869B-58D61F00DC74"

    ORM, , . , - find () , , , .

    , - update():

    var asset = new Asset({name: "foo"});asset.save();

    // assertEqual( Asset.find(asset.id).name, "foo" );

    // , update()asset.name = "wem";

    // ! ,

    // "wem"assertEqual( Asset.find(asset.id).name, "foo" );

    , f in d(). - :

    Asset.extend({find: function(id){var record = this.records[id];if ( !record ) throw("Hen3BecTHafl ");

    return record.dup();}

  • 8/11/2019 - - JavaScript - 2012.pdf

    62/285

    ORM 61

    });

    Asset.include({create: function(){this.newRecord = false;

    this.parent.records[this.id] = this.dup();b

    update: function(){this.parent.records[this.id] = this.dup();

    dup: function(){return jQuery.extend(true, {}, this);

    }

    ; : Model. records , :

    assertEqual( Asset.records, Person.records );

    :

    var asset = Asset.init();asset.save();

    assert( asset in Person.records );

    records . Model.created() - , , - :

    Model.extend({created: function(){this.records = {};

    }});

    , . , . - , - . , .

    , - .

  • 8/11/2019 - - JavaScript - 2012.pdf

    63/285

    62 3.

    , . -

    , . -, ( - ).

    , , - -? , , - ( ). , .

    , . , . , - , .

    - HTTP Ajax JSONP. , , . AJAX JSON HTML, -

    .

    , -, , . .

    JSON . - , Ruby on Rails :

    var User = {};User.records = ;

    ERB JSON . raw JSON. - HTML :

    var User = {};

    User.records = [{"first_name": "Alex"}];

  • 8/11/2019 - - JavaScript - 2012.pdf

    64/285

    ORM 63

    JavaScript JSON, , JavaScript.

    Ajax

    , , -, , : , . , Ajax - API , .

    Ajax XMLHttpRequest, - Getting Started Mozilla. , - , , , ,

    jQuery, Ajax API, . API jQuery, XMLHttpRequest .

    jQuery Ajax API jQuery.a jax() , , - . jQuery.ajax() , - . , - .

    url

    URL. ,

    success

    , . , .

    contentType

    ContentType. , application/x-www-form-urlencoded, .

    data

    , . , jQuery URL.

    type

    HTTP: GET, POST DELETE. - GET.

    dataType

    , . jQuery , ,

    . dataType , jQuery - MIME . :

  • 8/11/2019 - - JavaScript - 2012.pdf

    65/285

    64 3.

    text

    ; ,

    script

    jQuery JavaScript,

    json

    jQuery JSON, ,

    jsonp

    JSONP, .

    , , Ajax, , :

    jQuery.ajax({url: "/ajax/endpoint",type: "GET",success: function(data) {alert(data);

    }});

    . , jQuery . jQuery .get() URL, - :

    jQuery.get("/ajax/endpoint", function(data){$(".ajaxResult").text(data);

    ;

    GET :

    jQuery.get("/ajax/endpoint", {foo: "bar"}, function(data){/ * . . . * /

    ;

    JSON,

    jQuery. getDSON(), data - "json":

    jQuery.getDSON("/j son/endpoint", function(j son){

    });

    jQuery .post() , URL, - :

    jQuery.post(H/usersH, {first_name: "Alex"}, function(result){/* Ajax POST */

    });

  • 8/11/2019 - - JavaScript - 2012.pdf

    66/285

    ORM 65

    HTTP DELETE, HEAD OP-TIONS, jQuery.ajax().

    Ajax API, jQuery, , .

    Ajax (same origin poli-cy), , , , . : Ajax cookie . , - . Gmail, Facebook -

    , -.

    -, , . , Adobe Flash Java, , , Ajax , - CORS(crossorigin resource sharing).

    CORS , - . , IE6, .

    CORS :

    IE >= 8 ( )

    Firefox >= 3

    Safari:

    Chrome: Opera:

    CORS . , :

    Access-Control-Allow-Origin: example.comAccess-Control-Request-Method: GET,POST

    GET POST example.com. , GET, POST.

  • 8/11/2019 - - JavaScript - 2012.pdf

    67/285

    66 3.

    , - Access-Control-Allow-Origin, . , - (origin) (*).

    , Safari, OPTIONS, - . Firefox , CORS , . .

    , - Access-Control-Request-Headers:

    Access-Control-Request-Headers: Authorization

    , Ajax

    , OAuth:

    var req = new XMLHttpRequest();req.open("POST", "/endpoint", true);req.setRequestHeader("Authorization", oauth_signature);

    , CORS Internet Explorer 8 , Microsoft . Microsoft , XDomainRequest, XMLHttpRequest -

    . XMLHttpRequest, . , GET POST, , -, , ContentType: text/

    plain. , , Access-Control, CORS IE.

    JSONP JSONP, JSON (padding), -

    CORS . script, - JSON, . script -, .

    , script, :

    , data.json, JSON, :

    jsonCallback({"data": "foo"})

    http://example.com/data.jsonhttp://example.com/data.json
  • 8/11/2019 - - JavaScript - 2012.pdf

    68/285

    ORM 67

    . - , :

    window.jsonCallback = function(result){//

    >

    . , jQuery API:

    jQuery.getJSON("http://example.com/data.json?callback=?H, function(result)

    {//

    ;

    jQuery URL , -

    . , - .

    JSONP - , . - , , API , CORS JSONP

    . Ajax cookie , , API . , .

    CORS/JSONP , API, -:

    , , ;

    ( , ). , , - Auth.

    ORM ORM -. , . Model populate(),

    http://example.com/data.json?callback=?Hhttp://example.com/data.json?callback=?H
  • 8/11/2019 - - JavaScript - 2012.pdf

    69/285

    68 3.

    , records:

    Model.extend({populate: function(values){

    // model recordsthis.records = {};for (var i=0, il = values.length; i < il; i++) {var record = this.init(values[i]);record.newRecord = false;this.records[record.id] = record;

    }}

    });

    Model.populate()

    :

    jQuery.getJSON("/assets", function(result){Asset.populate(result);

    });

    ORM.

    . -

    cookie Adobe Flash. Cookie API - , , , . Flash, - .

    , HTML5, - . cookie , - .

    , , - (, , ), 5 :

    IE >*8

    Firefox >* 3.5

    Safari >= 4

    Chrome >= 4

    Opera >= 10.6

    HTML5 HTML5 (HTML5 Web Storage) : (local

  • 8/11/2019 - - JavaScript - 2012.pdf

    70/285

    ORM 69

    storage) (session storage). - , . , -

    . - , , , localStorage sessionStorage.API JavaScript , - , , - :

    // localStorage[,,someDataM] = "wem";

    API :// var itemsStored = localStorage.length;

    // ( -)localStorage.setltem("someData", "wem");

    // , null, localStorage.getItem("someData"); //=> "wem";

    // , null, localStorage.removeItem("someData");

    // ( )localStorage.clear();

    , , . JSON, JSON ( ),

    JSON :var object = {some: "object"};

    // localStorage.setItem("seriData", JSON.stringify(object));

    // var result = DSON.parse(loc^lStorage.getItem(MseriDataM));

    /

    ( 5 ),

    QUOTA_EXCEEDED_

    ERR.

  • 8/11/2019 - - JavaScript - 2012.pdf

    71/285

    70 3.

    ORM ORM, -

    . - localStorage, JSON. , :

    var json = JSON.stringify(Asset.init({name: "foo"}));json //=> "{"parent":{"parent":{"prototype":{}},"records":[]},"name":"foo"}"

    , JSON . , -. Model ,

    :Model.extend({

    created: function(){this.records = {};this.attributes = [];

    >});Asset.attributes = ["name", "ext"];

    , , attributes Model. - , , records.

    attributes() , - :

    Model.include({attributes: function(){var result = {};for(var i in this.parent.attributes) {var attr = this.parent.attributes[i];

    result[attr] = this[attr];>result.id = this.id;return result;

    }});

    :

    Asset.attributes = ["name", "ext"];

    attributes () :

    var asset = Asset.init({name: "document", ext: ".txt"});asset.attributesQ; //=> {name: "document", ext: ".txt"};

  • 8/11/2019 - - JavaScript - 2012.pdf

    72/285

    ORM 71

    JSON. stringify(), - to3SON() . JSON - , - records :

    Model.include({toJSON: function(){return(this.attributes());

    > ;

    . - JSON :

    var json = JSON.stringif(Asset.records);j son //= M{M7B2A9E8D...":"{"name":"document" ,"ext":".txt","id":"7B2A9E8D..."}"}"

    JSON, . Model : savel_ocal()H loadLocalQ. Model.records , localStorage:

    var Model.LocalStorage = {saveLocal: function(name){// var result = [];

    for (var i in this.records)result.push(this.records[i])

    localStorage[name] = JSON.stringify(result);

    bloadLocal: function(name){var result = DSON.parse(localStorage[name]);this.populate(result);

    >>;Asset.extend(Model.LocalStorage);

    , - . .

    jQuery post() - . : URL, :

    jQuery.post("/users", {first_name: "Alex"}, function(result){/* Ajax POST */

    });

  • 8/11/2019 - - JavaScript - 2012.pdf

    73/285

    72 3.

    , attributes() , - , POST :

    jQuery.post("/assets", asset.attributesQ, function(result){/* Ajax POST */

    ;

    REST , HTTP POST PUT . - Model : createRemoteQ updateRemoteQ, HTTP :

    Model.include({createRemote: function(url, callback){$.post(url, this.attributesQ, callback);

    bupdateRemote: function(url, callback){$.ajax({url: url,data: this.attributes(),success: callback,type: "PUT"

    ;>

    ;

    createRemote() Asset, POST :

    // :Asset.init({name: "jason.txt"}).createRemote("/assets");

  • 8/11/2019 - - JavaScript - 2012.pdf

    74/285

    , . , - cookie . JavaScript -

    , , .

    - . - , . - , JavaScript .

    . ? ? , DOM? , .

    DOM. , ! , - MVC, - .

    ? - . , - . , - .

    , - . - . , . .

  • 8/11/2019 - - JavaScript - 2012.pdf

    75/285

  • 8/11/2019 - - JavaScript - 2012.pdf

    76/285

    75

    , , . window , , - :

    (function($, exports){exports.Foo = "wem";})(jQuery, window);assertEqual( Foo, "wem" );

    , exports, , .

    - , . - this window:

    (function(){assertEqual( this, window );

    >)();

    , - . :

    (function(){var mod = {};

    mod.contextFunction = function(){assertEqual( this, mod );

    };

    mod.contextFunction();

    ( ) ;

    contextFunctionQ mod. this, . , , -:

    (function($){

    var mod = {};

    mod.load = function(func){

    $($.proxy(func, this)); &

  • 8/11/2019 - - JavaScript - 2012.pdf

    77/285

    76 4.

    mod.load(function(){this.view = $("#view");

    >);

    mod.assetsClick = function(e){

    // };mod.load(function(){this.view.find(".assets").click($.proxy(this.assetsClick, this)

    );});

    })(jQuery);

    load(), , - . , - jQuery.proxy ().

    , , - assetsClick(). . , - .

    , - . - load() proxy() include():

    (function($, exports){var mod = function(includes){

    if (includes) this.include(includes);

    };mod.fn = mod.prototype;

    mod.fn.proxy = function(func){

    return $.proxy(func, this);>;

    mod.fn.load = function(func){$(this.proxy(func));

    >;

    mod.fn.include = function(ob){$.extend(this, ob);

    };

    exports.Controller = mod;})(jQuery, window);

  • 8/11/2019 - - JavaScript - 2012.pdf

    78/285

    77

    proxy () , , . includeQ , .

    exports, - Controller. Controller , . - , cla ss :

    (function($, Controller){

    var mod = new Controller;

    mod.toggleClass = function(e){this.view.toggleClass("over", e.data);

    };

    mod.load(function(){this.view = $("#view");this.view.mouseover(this.proxy(this.toggleClass), true);this.view.mouseout(this.proxy(this.toggleClass), false);

    >);})(jQuery, Controller);

    , view - . , , togg leClass(), , c la ss . , , assets/ch04/modules.html.

    - , th is. - . , Controller, :

    Controller.fn.unload = function(func){jQuery(window).bind("unload", this.proxy(func));

    };

    includeQ , :

    var mod = new Controller;mod.include(StateMachine);

    StateMachine -

    , don't repeat yourself DRY ( ).

  • 8/11/2019 - - JavaScript - 2012.pdf

    79/285

    78 4.

    , - DOM, , . , - , .

    - DOM. , , - , DOM .

    , . Controller , -

    , - :

    // window // var exports = this;

    (function($){var mod = {};

    mod.create = function(includes){

    var result = function(){this.init.apply(this, arguments);

    };

    result.fn = result.prototype;result.fn.init = function(){};

    result.proxy = function(func){ return $.proxy(func, this); };result.fn.proxy = result.proxy;

    result.include = function(ob){ $.extend(this.fn, ob); };result.extend = function(ob){ $.extend(this, ob); };if (includes) result.include(includes)

    return result;

    >;

    exports.Controller = modj})(jQuery);

    Controller.createQ

    , . - , jQuery(function(){ /* ... */}).

  • 8/11/2019 - - JavaScript - 2012.pdf

    80/285

    79

    jQuery. ready() , , DOM :

    jQuery(function($){var ToggleView = Controller.create({

    init: function(view){this.view = $(view);this.view.mouseover(this.proxy(this.toggleClass), true);this.view.mouseout(this.proxy(this.toggleClass), false);

    b

    this.toggleClass: function(e){this.view.toggleClass("over", e.data);

    >>);

    // Instantiate controller, calling init()new ToggleViewC'tview");

    >);

    - . , , - , .

    , -. (ID), . ID class, . , .

    -

    jQuery(), . - , :

    / / . . .init: function(view){this.view = $(view);this.form = this.view.find("form");

    >

    , , DOM. ,

  • 8/11/2019 - - JavaScript - 2012.pdf

    81/285

    80 4.

    , -:

    elements: {"form.searchForm": "searchForm",

    "form input[type=text]": "searchlnput"}

    , this.searchForm this.searchlnput - . jQuery, , .

    , -

    . init(), :

    var exports = this;jQuery(function($){exports.SearchView = Controller.create({// elements: {

    "input[type=search]": "searchlnput","form": "searchForm"

    b

    // init: function(element){this.el = $(element);this.refreshElements();this.searchForm.submit(this.proxy(this.search));

    bsearch: function(){console.log("Searching:", this.searchlnput.val());

    b// $: function(selector){// 'el' return $(selector, this.el);

    // refreshElements: function(){for (var key in this.elements) {this[this.elements[key]] = this.$(key);

    }}

    });

    new SearchView("#users");});

  • 8/11/2019 - - JavaScript - 2012.pdf

    82/285

    81

    refreshElements() el, . ref reshElements() this.searchForm this.searchlnput, -

    DOM. , , assets/ch04/views.html.

    - (proxying) events, . elements, , :

    events: {"submit form": "submit"

    }

    SearchView. refreshElements(), delegateEvents(), . , . Search View search(), - :

    var exports = this;jQuery(function($){exports.SearchView = Controller.create({// ,// events: {

    "submit form": "search"

    init: function(){

    / / ...this.delegateEvents();

    b

    search: function(e){ /*...*/},

    //

    // eventSplitter: /A(\w+)\s*(.*)$/,

    delegateEvents: function(){ &

  • 8/11/2019 - - JavaScript - 2012.pdf

    83/285

    82 4.

    for (var key in this.events) {var methodName = this.events[key];var method = this.proxy(this[methodName]);

    var match * key.match(this.eventSplitter);

    var eventName = matchfl], selector = match[2];

    if (selector === '') {this.el.bind(eventName, method);

    } else {this.el.delegate(selector, eventName, method);

    }}

    } ;

    , delegate(), bindQ delegateEvent