Even more JavaScript best practices @GregWeng NCU 2015/10/23
Today's lesson
Comment in JSDoc Style Racing Event queuing & Abortable Promise ES6/7/8 & Babel Homework review
JSDoc https://github.com/gitgrimbo/jsdoc3-examples http://usejsdoc.org/
Generate (pretty) API documents for human
If you follow its comment format
Demo site of Gaia System app http://alivedise.github.io/gaia-system-jsdoc/
Good first bugs for adding JSDoc comment https://bugzilla.mozilla.org/show_bug.cgi?id=1170465 It is a good way to learn contribution
Racing & Abortable Promise
Racing System Booting passcode.enabled Screen Lock Shows up reading Lock with Passcode return value Booting Logo Screen Lock Initializing ~ 3 seconds
passcode.enabled Screen Lock Shows up reading Lock with Passcode return value Screen Lock Initializing ~ 3 seconds Racing System Booting Booting Logo Racing
Whenever there is a "guessing" about some async operations...
A racing is held
And the solution is not trivial...
Bug 1173284 100+ comments & 1 month
passcode.enabled Screen Lock Shows up reading Lock with Passcode return value Screen Lock Initializing ~ 3 seconds Solution System Booting Booting Logo Freeze the slider
Event queueing & Abortable Promise
Public interfaces of JavaScript program components JavaScript components usually use handlers as public interfaces among the user, server and other components like to draw or to fire new events private helper methods... event handlers server gateway local data keeper component usernative events server sync componentscustom events
Or racing may occur when two events and their async operations are performing handler bar handler foo "handleEvent" component Async event handlers need a queue async helper sync helper handling foo waiting to handle bar waiting to handle foo waiting to handle foo waiting to handle bar event comes when there is one being handled
Promise as the queue
Every handler will be queued by concating them with the 'then' method handler bar handler foo "handleEvent" component Promise as the queue async helper sync helper event comes when there is one being handled this.mainPromise = this. mainPromise.then( this.handlerBar.bind(this) ); handling foo waiting to handle bar waiting to handle foo
Promise is not enough when events are prioritized
Must not be queued: handle it immediately and clear all queued steps handler bar handler foo "handleEvent" component Prioritized events async helper sync helper handling bar waiting to handle bar waiting to handle foo waiting to handle bar waiting to handle bar
How to clear the queued steps? handler bar handler foo "handleEvent" component Prioritized events async helper sync helper waiting to handle bar handling foo waiting to handle bar waiting to handle bar waiting to handle bar
Promise/A+ spec doesn't provide any method to abort it...
Need to create a "Process" to wrap the original Promise
Throw an "Interrupt" customized error when prioritized event comes, and capture it later to silent the error console handler bar handler foo "handleEvent" component Prioritized events with "Process" async helper sync helper waiting to handle bar handling foo waiting to handle bar waiting to handle bar waiting to handle bar Error: Interrupt
ES6/7/8 & Babel
import Utils from 'js/utils' export default class { constructor(id) { this.id = id this.queue = Promise.resolve() } handleEvent(event) { this.queue = this.queue.then(() => { return this.onEvent[event.type].bind(this) }).catch((err) => { this.onErrorOrInterrupt(err) }) } }
EcmaScript transpiler Babel
https://babeljs.io/
In the current front-end world ES6+ is becoming the mainstream
Homework review
Please do not test expression only: About the test it('will test some pure functions', function() { assert(2 === (1 + 1)); }); it('will test some pure functions', function() { var manager = new Manager() assert(2 === manager.pureAdd(1, 1)); }); //.... Manager.prototype.pureAdd = function(a, b) { return a + b; };
It is not necessary to bind then call it immediately About the 'bind' handleEvent(event) { .... case 'foo': this.onEventFoo.bind(this)() } window.addEventListener('foo', this); // Bind `this` to the handleEvent //.... handleEvent(event) { .... case 'foo': this.onEventFoo() // `this` of 'handleEvent' is already bound }
The `then` method will pass the argument, and bound function can still be called as normal function, so: About the Promise + 'bind' .then(function(data) { this.foo(data); }.bind(this)); .then(this.foo.bind(this));
Please give it a clear naming convention to distinguish constructor and instance Naming convention is important var foo = function() {}; var f = new foo(); //.... var Foo = function() {}; var foo = new Foo(); //....
You are in trouble if your PR show some red lines like this and you can't explain that
And please comment on PR or using commits to indicate what issue you're addressing
Update: people who already commented on PRs Quiz#1 rockwyc992 : 吳易璋 CaeserNieh : 聶順成 rockwyc992 : 吳易璋 Quiz#2 jason1122g : 邱義傑 bdsword : 蔣彥亭 c910335 : 陳達仁 Davisanity : 林唐正 amm040341 : 蘇聖雅 rueian : 黃瑞安 w181496 : 黃詩凱 Peter654q :莊侑穎 bdsword : 蔣彥亭 Quiz#3 rueian : 黃瑞安 c910335 : 陳達仁 CrashedBboy : 吳承霖 Sharknevercries : 李政遠 jason1122g : 邱義傑

Even more java script best practices

  • 1.
    Even more JavaScript bestpractices @GregWeng NCU 2015/10/23
  • 2.
  • 3.
    Comment in JSDocStyle Racing Event queuing & Abortable Promise ES6/7/8 & Babel Homework review
  • 4.
  • 5.
    Generate (pretty) APIdocuments for human
  • 6.
    If you followits comment format
  • 7.
    Demo site ofGaia System app http://alivedise.github.io/gaia-system-jsdoc/
  • 8.
    Good first bugsfor adding JSDoc comment https://bugzilla.mozilla.org/show_bug.cgi?id=1170465 It is a good way to learn contribution
  • 9.
  • 10.
    Racing System Booting passcode.enabled Screen Lock Shows up readingLock with Passcode return value Booting Logo Screen Lock Initializing ~ 3 seconds
  • 11.
    passcode.enabled Screen Lock Shows up readingLock with Passcode return value Screen Lock Initializing ~ 3 seconds Racing System Booting Booting Logo Racing
  • 12.
    Whenever there isa "guessing" about some async operations...
  • 13.
  • 14.
    And the solutionis not trivial...
  • 15.
  • 16.
    passcode.enabled Screen Lock Shows up readingLock with Passcode return value Screen Lock Initializing ~ 3 seconds Solution System Booting Booting Logo Freeze the slider
  • 17.
    Event queueing &Abortable Promise
  • 18.
    Public interfaces ofJavaScript program components JavaScript components usually use handlers as public interfaces among the user, server and other components like to draw or to fire new events private helper methods... event handlers server gateway local data keeper component usernative events server sync componentscustom events
  • 19.
    Or racing mayoccur when two events and their async operations are performing handler bar handler foo "handleEvent" component Async event handlers need a queue async helper sync helper handling foo waiting to handle bar waiting to handle foo waiting to handle foo waiting to handle bar event comes when there is one being handled
  • 20.
  • 21.
    Every handler willbe queued by concating them with the 'then' method handler bar handler foo "handleEvent" component Promise as the queue async helper sync helper event comes when there is one being handled this.mainPromise = this. mainPromise.then( this.handlerBar.bind(this) ); handling foo waiting to handle bar waiting to handle foo
  • 22.
    Promise is notenough when events are prioritized
  • 23.
    Must not bequeued: handle it immediately and clear all queued steps handler bar handler foo "handleEvent" component Prioritized events async helper sync helper handling bar waiting to handle bar waiting to handle foo waiting to handle bar waiting to handle bar
  • 24.
    How to clearthe queued steps? handler bar handler foo "handleEvent" component Prioritized events async helper sync helper waiting to handle bar handling foo waiting to handle bar waiting to handle bar waiting to handle bar
  • 25.
    Promise/A+ spec doesn'tprovide any method to abort it...
  • 26.
    Need to createa "Process" to wrap the original Promise
  • 27.
    Throw an "Interrupt"customized error when prioritized event comes, and capture it later to silent the error console handler bar handler foo "handleEvent" component Prioritized events with "Process" async helper sync helper waiting to handle bar handling foo waiting to handle bar waiting to handle bar waiting to handle bar Error: Interrupt
  • 28.
  • 29.
    import Utils from'js/utils' export default class { constructor(id) { this.id = id this.queue = Promise.resolve() } handleEvent(event) { this.queue = this.queue.then(() => { return this.onEvent[event.type].bind(this) }).catch((err) => { this.onErrorOrInterrupt(err) }) } }
  • 30.
  • 31.
  • 32.
    In the currentfront-end world ES6+ is becoming the mainstream
  • 33.
  • 34.
    Please do nottest expression only: About the test it('will test some pure functions', function() { assert(2 === (1 + 1)); }); it('will test some pure functions', function() { var manager = new Manager() assert(2 === manager.pureAdd(1, 1)); }); //.... Manager.prototype.pureAdd = function(a, b) { return a + b; };
  • 35.
    It is notnecessary to bind then call it immediately About the 'bind' handleEvent(event) { .... case 'foo': this.onEventFoo.bind(this)() } window.addEventListener('foo', this); // Bind `this` to the handleEvent //.... handleEvent(event) { .... case 'foo': this.onEventFoo() // `this` of 'handleEvent' is already bound }
  • 36.
    The `then` methodwill pass the argument, and bound function can still be called as normal function, so: About the Promise + 'bind' .then(function(data) { this.foo(data); }.bind(this)); .then(this.foo.bind(this));
  • 37.
    Please give ita clear naming convention to distinguish constructor and instance Naming convention is important var foo = function() {}; var f = new foo(); //.... var Foo = function() {}; var foo = new Foo(); //....
  • 38.
    You are introuble if your PR show some red lines like this and you can't explain that
  • 39.
    And please commenton PR or using commits to indicate what issue you're addressing
  • 40.
    Update: people whoalready commented on PRs Quiz#1 rockwyc992 : 吳易璋 CaeserNieh : 聶順成 rockwyc992 : 吳易璋 Quiz#2 jason1122g : 邱義傑 bdsword : 蔣彥亭 c910335 : 陳達仁 Davisanity : 林唐正 amm040341 : 蘇聖雅 rueian : 黃瑞安 w181496 : 黃詩凱 Peter654q :莊侑穎 bdsword : 蔣彥亭 Quiz#3 rueian : 黃瑞安 c910335 : 陳達仁 CrashedBboy : 吳承霖 Sharknevercries : 李政遠 jason1122g : 邱義傑