顯示具有 程式-JavaScript 標籤的文章。 顯示所有文章
顯示具有 程式-JavaScript 標籤的文章。 顯示所有文章

2017年10月18日 星期三

Functional Programming in Javascript

This is a series of interactive exercises for learning Microsoft's Reactive Extensions (Rx) Library for Javascript. So why is the title "Functional Programming in Javascript"? Well it turns out that the key to learning Rx is training yourself to use functional programming to manipulate collections. Functional programming provides developers with the tools to abstract common collection operations into reusable, composable building blocks. You'll be surprised to learn that most of the operations you perform on collections can be accomplished with five simple functions:
  1. map
  2. filter
  3. mergeAll
  4. reduce
  5. zip
Here's my promise to you: if you learn these 5 functions your code will become shorter, more self-descriptive, and more durable. Also, for reasons that might not be obvious right now, you'll learn that these five functions hold the key to simplifying asynchronous programming. Once you've finished this tutorial you'll also have all the tools you need to easily avoid race conditions, propagate and handle asynchronous errors, and sequence events and AJAX requests. In short, these 5 functions will probably be the most powerful, flexible, and useful functions you'll ever learn.

from : https://github.com/ReactiveX/learnrx

2017年9月17日 星期日

Headless Chrome Node API

page : https://github.com/GoogleChrome/puppeteer

2017年4月10日 星期一

Target="_blank" - the most underestimated vulnerability ever

People using target='_blank' links usually have no idea about this curious fact:
The page we're linking to gains partial access to the linking page via the window.opener object.
The newly opened tab can, say, change the window.opener.location to some phishing page. Or execute some JavaScript on the opener-page on your behalf... Users trust the page that is already opened, they won't get suspicious.
Example attack: create a fake "viral" page with cute cat pictures, jokes or whatever, get it shared on Facebook (which is known for opening links via _blank) and every time someone clicks the link - execute
window.opener.location = 'https://fakewebsite/facebook.com/PHISHING-PAGE.html';
…redirecting to a page that asks the user to re-enter her Facebook password.

How to fix

Add this to your outgoing links.
rel="noopener"
Update: FF does not support "noopener" so add this.
rel="noopener noreferrer"
Remember, that every time you open a new window via window.open(); you're also "vulnerable" to this, so always reset the "opener" property
var newWnd = window.open();
newWnd.opener = null;
PS. Interestingly, Google doesn't seem to care.

from : https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/

2014年5月4日 星期日

Result of toJSON() on a date is different between IE8 and IE9+

Prior to ES5, parsing of dates was entirely implementation dependent. IE 8 (and lower) won't parse the ISO 8601 format specified in ES5, so just parse it yourself:
// parse ISO format date like 2013-05-06T22:00:00.000Z
function dateFromISO(s) {
  s = s.split(/\D/);
  return new Date(Date.UTC(s[0], --s[1]||'', s[2]||'', s[3]||'', s[4]||'', s[5]||'', s[6]||''))
}
Assumes the string is UTC.

reference : http://stackoverflow.com/questions/17592717/result-of-tojson-on-a-date-is-different-between-ie8-and-ie9

2014年1月2日 星期四

html5shiv

HTML5 IE enabling script

reference : https://code.google.com/p/html5shiv/

2013年12月9日 星期一

Javascript show Server UTC time code

/*
 * A javascript extension to allow formatting of Date object like in Ruby's strftime.
Documentation http://www.ruby-doc.org/core/classes/Time.html#M000392
It's simple:
    new Date().format("%H:%M on %d/%m") returns "08:20 on 26/04"

Format directives:
Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (rounded down such as 20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..60)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  milli second (3 digits)
          %6N  micro second (6 digits)
          %9N  nano second (9 digits)
          %12N pico second (12 digits)
          %15N femto second (15 digits)
          %18N atto second (18 digits)
          %21N zepto second (21 digits)
          %24N yocto second (24 digits)

Time zone:
  %z - Time zone as hour and minute offset from UTC (e.g. +0900)
          %:z - hour and minute offset from UTC with a colon (e.g. +09:00)
          %::z - hour, minute and second offset from UTC (e.g. +09:00:00)
  %Z - Abbreviated time zone name or similar information.

Weekday:
  %A - The full weekday name (``Sunday'')
          %^A  uppercased (``SUNDAY'')
  %a - The abbreviated name (``Sun'')
          %^a  uppercased (``SUN'')
  %u - Day of the week (Monday is 1, 1..7)
  %w - Day of the week (Sunday is 0, 0..6)

ISO 8601 week-based year and week number:
The first week of YYYY starts with a Monday and includes YYYY-01-04.
The days in the year before the first week are in the last week of
the previous year.
  %G - The week-based year
  %g - The last 2 digits of the week-based year (00..99)
  %V - Week number of the week-based year (01..53)

Week number:
The first week of YYYY that starts with a Sunday or Monday (according to %U
or %W). The days in the year before the first week are in week 0.
  %U - Week number of the year. The week starts with Sunday. (00..53)
  %W - Week number of the year. The week starts with Monday. (00..53)

Seconds since the Epoch:
  %s - Number of seconds since 1970-01-01 00:00:00 UTC.

Literal string:
  %n - Newline character (\n)
  %t - Tab character (\t)
  %% - Literal ``%'' character

Combination:
  %c - date and time (%a %b %e %T %Y)
  %D - Date (%m/%d/%y)
  %F - The ISO 8601 date format (%Y-%m-%d)
  %v - VMS date (%e-%^b-%4Y)
  %x - Same as %D
  %X - Same as %T
  %r - 12-hour time (%I:%M:%S %p)
  %R - 24-hour time (%H:%M)
  %T - 24-hour time (%H:%M:%S)
 */
(function () {
    var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
    
    var re = new RegExp(/%(a|A|b|B|c|C|d|D|e|F|h|H|I|j|k|l|L|m|M|n|p|P|r|R|s|S|t|T|u|U|v|V|W|w|x|X|y|Y|z)/g);
    var abbreviatedWeekdays = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];
    var fullWeekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var abbreviatedMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var fullMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    
    function padNumber(num, count, padCharacter) {
      if (typeof padCharacter == "undefined") {
        padCharacter = "0";
      }
      var lenDiff = count - String(num).length;
      var padding = "";
    
      if (lenDiff > 0)
        while (lenDiff--)
          padding += padCharacter;
          
      return padding + num;
    }
    
    function dayOfYearUTC(d) {
      var oneJan = new Date(d.getUTCFullYear(), 0, 1);
      return Math.ceil((d - oneJan) / 86400000);
    }
    
    function weekOfYearUTC(d) {
      var oneJan = new Date(d.getUTCFullYear(), 0, 1);
      return Math.ceil((((d - oneJan) / 86400000) + oneJan.getUTCDay() + 1) / 7);
    }
    
    function isoWeekOfYearUTC(d) {
      var target  = new Date(d.valueOf());  
      var dayNr   = (d.getUTCDay() + 6) % 7;  
      target.setDate(target.getUTCDate() - dayNr + 3);  
      var jan4    = new Date(target.getUTCFullYear(), 0, 4);  
      var dayDiff = (target - jan4) / 86400000;
      
      return 1 + Math.ceil(dayDiff / 7);
    }
    
    function tweleveHourUTC(d) {
      return d.getUTCHours() > 12 ? d.getUTCHours() - 12 : d.getUTCHours();
    }
    
    function timeZoneOffset(d) {
      var hoursDiff = (-d.getTimezoneOffset() / 60);
      var result = padNumber(Math.abs(hoursDiff), 4);
      return (hoursDiff > 0 ? "+" : "-") + result;
    }
    
    Date.prototype.formatUTC = function (formatString) {
      return formatString.replace(re, __bind(function (m, p) {
        switch (p) {
          case "a": return abbreviatedWeekdays[this.getUTCDay()];
          case "A": return fullWeekdays[this.getUTCDay()];
          case "b": return abbreviatedMonths[this.getUTCMonth()];
          case "B": return fullMonths[this.getUTCMonth()];
          case "c": return this.toLocaleString();
          case "C": return Math.round(this.getUTCFullYear() / 100);
          case "d": return padNumber(this.getUTCDate(), 2);
          case "D": return this.format("%m/%d/%y");
          case "e": return padNumber(this.getUTCDate(), 2, " ");
          case "F": return this.format("%Y-%m-%d");
          case "h": return this.format("%b");
          case "H": return padNumber(this.getUTCHours(), 2);
          case "I": return padNumber(tweleveHourUTC(this), 2);
          case "j": return padNumber(dayOfYearUTC(this), 3);
          case "k": return padNumber(this.getUTCHours(), 2, " ");
          case "l": return padNumber(tweleveHourUTC(this), 2, " ");
          case "L": return padNumber(this.getUTCMilliseconds(), 3);
          case "m": return padNumber(this.getUTCMonth() + 1, 2);
          case "M": return padNumber(this.getUTCMinutes(), 2);
          case "n": return "\n";
          case "p": return this.getUTCHours() > 11 ? "PM" : "AM";
          case "P": return this.format("%p").toLowerCase();
          case "r": return this.format("%I:%M:%S %p");
          case "R": return this.format("%H:%M");
          case "s": return this.getTime() / 1000;
          case "S": return padNumber(this.getUTCSeconds(), 2);
          case "t": return "\t";
          case "T": return this.format("%H:%M:%S");
          case "u": return this.getUTCDay() == 0 ? 7 : this.getUTCDay();
          case "U": return padNumber(weekOfYearUTC(this), 2); //either this or W is wrong (or both)
          case "v": return this.format("%e-%b-%Y");
          case "V": return padNumber(isoWeekOfYearUTC(this), 2);
          case "W": return padNumber(weekOfYearUTC(this), 2); //either this or U is wrong (or both)
          case "w": return padNumber(this.getUTCDay(), 2);
          case "x": return this.toLocaleDateString();
          case "X": return this.toLocaleTimeString();
          case "y": return String(this.getUTCFullYear()).substring(2);
          case "Y": return this.getUTCFullYear();
          case "z": return timeZoneOffset(this);
          default: return match;
        }
      }, this));
    };

}).call(this);

2013年11月28日 星期四

Charting Library - Data-Driven Documents

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.

reference : http://d3js.org/

2013年11月17日 星期日

Organizing your application using Modules (require.js, backbone.js)

Tutorial

Organizing your application using Modules (require.js)

Unfortunately Backbone.js does not tell you how to organize your code, leaving many developers in the dark regarding how to load scripts and lay out their development environments.
This was quite a different decision to other JavaScript MVC frameworks who were more in favor of setting a development philosophy.
Hopefully this tutorial will allow you to build a much more robust project with great separation of concerns between design and code.
This tutorial will get you started on combining Backbone.js with AMD (Asynchronous Module Definitions).

What is AMD?

Asynchronous Module Definitions designed to load modular code asynchronously in the browser and server. It is actually a fork of the Common.js specification. Many script loaders have built their implementations around AMD, seeing it as the future of modular JavaScript development.
This tutorial will use Require.js to implement a modular and organized Backbone.js.
I highly recommend using AMD for application development
Quick Overview

Why Require.js?

p. Require.js has a great community and it is growing rapidly. James Burke the author is married to Require.js and always responds to user feedback. He is a leading expert in script loading and a contributer to the AMD specification.

Getting started

To easily understand this tutorial you should jump straight into the example code base.
The tutorial is only loosely coupled with the example and you will find the example to be more comprehensive.
If you would like to see how a particular use case would be implemented please visit the GitHub page and create an issue.(Example Request: How to do nested views).
The example isn't super fleshed out but should give you a vague idea.

Example File Structure

There are many different ways to lay out your files and I believe it is actually dependent on the size and type of the project. In the example below views and templates are mirrored in file structure. Collections and Models are categorized into folders kind of like an ORM.
/* File Structure
├── imgs
├── css
│   └── style.css
├── templates
│   ├── projects
│   │   ├── list.html
│   │   └── edit.html
│   └── users
│       ├── list.html
│       └── edit.html
├── js
│   ├── libs
│   │   ├── jquery
│   │   │   ├── jquery.min.js
│   │   ├── backbone
│   │   │   ├── backbone.min.js
│   │   └── underscore
│   │   │   ├── underscore.min.js
│   ├── models
│   │   ├── users.js
│   │   └── projects.js
│   ├── collections
│   │   ├── users.js
│   │   └── projects.js
│   ├── views
│   │   ├── projects
│   │   │   ├── list.js
│   │   │   └── edit.js
│   │   └── users
│   │       ├── list.js
│   │       └── edit.js
│   ├── router.js
│   ├── app.js
│   ├── main.js  // Bootstrap
│   ├── order.js //Require.js plugin
│   └── text.js  //Require.js plugin
└── index.html

*/
To continue you must really understand what we are aiming towards as described in the introduction.

Bootstrapping your application

Using Require.js we define a single entry point on our index page. We should setup any useful containers that might be used by our Backbone views.
Note: The data-main attribute on our single script tag tells Require.js to load the script located at "js/main.js". It automatically appends the ".js"

 lang="en">

    </span>Jackie Chan<span class="nt" style="box-sizing: border-box; color: rgb(0, 0, 128);">
    
    
id="container">
id="menu">
id="content">
You should most always end up with quite a light weight index file. You can serve this off your server and then the rest of your site off a CDN ensuring that everything that can be cached, will be. (You can also now serve the index file off the CDN using Cloudfront)

What does the bootstrap look like?

Our bootstrap file will be responsible for configuring Require.js and loading initially important dependencies.
In the example below we configure Require.js to create a shortcut alias to commonly used scripts such as jQuery, Underscore and Backbone.
Unfortunately Backbone.js isn't AMD enabled so I downloaded the community managed repository and patched it on amdjs.
Hopefully if the AMD specification takes off these libraries will add code to allow themselves to be loaded asynchronously. Due to this inconvenience the bootstrap is not as intuitive as it could be.
We also request a module called "app", this will contain the entirety of our application logic.
Note: Modules are loaded relatively to the boot strap and always append with ".js". So the module "app" will load "app.js" which is in the same directory as the bootstrap.
// Filename: main.js

// Require.js allows us to configure shortcut alias
// There usage will become more apparent further along in the tutorial.
require.config({
  paths: {
    jquery: 'libs/jquery/jquery',
    underscore: 'libs/underscore/underscore',
    backbone: 'libs/backbone/backbone'
  }

});

require([

  // Load our app module and pass it to our definition function
  'app',
], function(App){
  // The "app" dependency is passed in as "App"
  App.initialize();
});

How should we lay out external scripts?

Any modules we develop for our application using AMD/Require.js will be asynchronously loaded.
We have a heavy dependency on jQuery, Underscore and Backbone, unfortunately this libraries are loaded synchronously and also depend on each other existing in the global namespace.

A boiler plate module

So before we start developing our application, let's quickly look over boiler plate code that will be reused quite often.
For convenience sake I generally keep a "boilerplate.js" in my application root so I can copy it when I need to.
//Filename: boilerplate.js

define([
  // These are path alias that we configured in our bootstrap
  'jquery',     // lib/jquery/jquery
  'underscore', // lib/underscore/underscore
  'backbone'    // lib/backbone/backbone
], function($, _, Backbone){
  // Above we have passed in jQuery, Underscore and Backbone
  // They will not be accessible in the global scope
  return {};
  // What we return here will be used by other modules
});
The first argument of the define function is our dependency array, in the future we can pass in any modules we like.

App.js Building our applications main module

Our applications main module should always remain light weight. This tutorial only covers setting up a Backbone Router and initializing it in our main module.
The router will then load the correct dependencies depending on the current URL.
// Filename: app.js
define([
  'jquery',
  'underscore',
  'backbone',
  'router', // Request router.js
], function($, _, Backbone, Router){
  var initialize = function(){
    // Pass in our Router module and call it's initialize function
    Router.initialize();
  }

  return {
    initialize: initialize
  };
});
// Filename: router.js
define([
  'jquery',
  'underscore',
  'backbone',
  'views/projects/list',
  'views/users/list'
], function($, _, Backbone, ProjectListView, UserListView){
  var AppRouter = Backbone.Router.extend({
    routes: {
      // Define some URL routes
      '/projects': 'showProjects',
      '/users': 'showUsers',

      // Default
      '*actions': 'defaultAction'
    }
  });

  var initialize = function(){
    var app_router = new AppRouter;
    app_router.on('showProjects', function(){
      // Call render on the module we loaded in via the dependency array
      // 'views/projects/list'
      var projectListView = new ProjectListView();
      projectListView.render();
    });
      // As above, call render on our loaded module
      // 'views/users/list'
    app_router.on('showUsers', function(){
      var userListView = new UserListView();
      userListView.render();
    });
    app_router.on('defaultAction', function(actions){
      // We have no matching route, lets just log what the URL was
      console.log('No route:', actions);
    });
    Backbone.history.start();
  };
  return {
    initialize: initialize
  };
});

Modularizing a Backbone View

Backbone views usually interact with the DOM. Using our new modular system we can load in JavaScript templates using the Require.js text! plug-in.
// Filename: views/project/list
define([
  'jquery',
  'underscore',
  'backbone',
  // Using the Require.js text! plugin, we are loaded raw text
  // which will be used as our views primary template
  'text!templates/project/list.html'
], function($, _, Backbone, projectListTemplate){
  var ProjectListView = Backbone.View.extend({
    el: $('#container'),
    render: function(){
      // Using Underscore we can compile our template with data
      var data = {};
      var compiledTemplate = _.template( projectListTemplate, data );
      // Append our compiled template to this Views "el"
      this.$el.append( compiledTemplate );
    }
  });
  // Our module now returns our view
  return ProjectListView;
});
JavaScript templating allows us to separate the design from the application logic by placing all our HTML in the templates folder.

Modularizing a Collection, Model and View

Now we put it altogether by chaining up a Model, Collection and View which is a typical scenario when building a Backbone.js application.
First we will define our model
// Filename: models/project
define([
  'underscore',
  'backbone'
], function(_, Backbone){
  var ProjectModel = Backbone.Model.extend({
    defaults: {
      name: "Harry Potter"
    }
  });
  // Return the model for the module
  return ProjectModel;
});
Now that we have a model, our collection module can depend on it. We will set the "model" attribute of our collection to the loaded module. Backbone.js offers great benefits when doing this.
Collection.model: Override this property to specify the model class that the collection contains. If defined, you can pass raw attributes objects (and arrays) to add, create, and reset, and the attributes will be converted into a model of the proper type.
// Filename: collections/projects
define([
  'underscore',
  'backbone',
  // Pull in the Model module from above
  'models/project'
], function(_, Backbone, ProjectModel){
  var ProjectCollection = Backbone.Collection.extend({
    model: ProjectModel
  });
  // You don't usually return a collection instantiated
  return ProjectCollection;
});
Now we can simply depend on our collection in our view and pass it to our JavaScript template.
// Filename: views/projects/list
define([
  'jquery',
  'underscore',
  'backbone',
  // Pull in the Collection module from above
  'collections/projects',
  'text!templates/projects/list.html'
], function($, _, Backbone, ProjectsCollection, projectsListTemplate){
  var ProjectListView = Backbone.View.extend({
    el: $("#container"),
    initialize: function(){
      this.collection = new ProjectsCollection();
      this.collection.add({ name: "Ginger Kid"});
      // Compile the template using Underscores micro-templating
      var compiledTemplate = _.template( projectsListTemplate, { projects: this.collection.models } );
      this.$el.html(compiledTemplate);
    }
  });
  // Returning instantiated views can be quite useful for having "state"
  return ProjectListView;
});

Conclusion

Looking forward to feedback so I can turn this post and example into quality references on building modular JavaScript applications.
Get in touch with me on twitter, comments or GitHub!

reference : http://backbonetutorials.com/organizing-backbone-using-modules/

wibiya widget