Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Streamline your web app with AmplifyJS

Streamline your web app with AmplifyJS

Ralph Whitbeck

May 25, 2012
Tweet

More Decks by Ralph Whitbeck

Other Decks in Programming

Transcript

  1. RALPH WHITBECK APPENDTO • AmplifyJS came out of appendTo’s need

    for: • solving common web application tasks • client/internal project development • simple API abstractions for: • Client Side Component Communications (Pub/Sub) • Client Side Browser & Mobile Device Storage (Store) • Ajax Request Management (Request)
  2. RALPH WHITBECK AMPLIFYJS IS ... • A set of JavaScript

    Components • Pub/Sub: amplify.publish, amplify.subscribe • Local storage: amplify.store • Request data: amplify.request
  3. RALPH WHITBECK SIMPLE PUB/SUB SYNTAX amplify.subscribe(“publishexample”,  function()  {    

       alert(  “publishexample  topic  published”); }); //  ... amplify.publish(“publishexample”);
  4. RALPH WHITBECK AMPLIFY’S PUB/SUB • Is often referred to as

    the core of the library • amplify.publish and amplify.subscribe facilitate the Publish and Subscribe messaging pattern • Someone broadcasts (publish) / Someone else listens (subscribes) • Separating logic allows for loose coupling of your components • Results in less brittle more reusable code
  5. RALPH WHITBECK USAGE amplify.subscribe(  string  topic,  function  callback  ); amplify.subscribe(

     string  topic,  object  context,  function  callback  ); amplify.subscribe(  string  topic,  function  callback,  number  priority); amplify.subscribe(  string  topic,  object  context,  function  callback,                                        number  priority); • topic: Name of the message to subscribe to. • [context]: What this will be when the callback is invoked. • callback: Function to invoke when the message is published. • [priority]: Priority relative to other subscriptions for the same message.
  6. RALPH WHITBECK PUB/SUB WITH CONTEXT AND DATA amplify.subscribe(  “contextdata”,  $(“p:first”),

     function(  data  )  {        this.text(  data.newtext  ); }); //  ... amplify.publish(  “contextdata”,  {  newtext:  “This  is  new  text.”  }  ); //  Multiple  data  parameters amplify.subscribe(  “multipleparams”,  function(  data1,  data2  )  {  ...  }); //  ... amplify.publish(  “multipleparams”,  “foo”,  “bar”  );
  7. RALPH WHITBECK SETTING PRIORITY amplify.subscribe(  “priorityexample”,  function  (param)  {  ...

     }  ); //... amplify.subscribe(  “priorityexample”,  function  (param)  {          if  (  param  ===  null  ||  param  ===  undefined  )  {                return  false;        } },  1  ); //... amplify.publish(  “priorityexample”,  someVariable  );
  8. RALPH WHITBECK ABSTRACTED LOCALSTORAGE amplify.store(  "employeeName",  "Ralph  Whitbeck"  ); amplify.store(

     "Employee",  {  fullName      :  "Ralph  Whitbeck",                                                            startDate    :  "October  24,  2011",                                                          position      :  "Senior  Developer"  });
  9. RALPH WHITBECK AMPLIFY’S STORE • Wrapper for various client-side storage

    systems • Consistent API that handles storage cross-browser • Utilizes latest storage technologies for those browser that have them • Degrades gracefully for browsers without support • Passively/explicitly choose the storage type to use • Serializes to/from JavaScript objects using JSON serialization
  10. RALPH WHITBECK STORAGE TYPES • Amplify Supports the following storage

    types: • localStorage • sessionStorage • globalStorage • userData • memory
  11. RALPH WHITBECK SUPPORTED BROWSERS • localStorage • IE 8+ •

    Firefox 3.5+ • Safari 4+ • Chrome • Opera 10.5+ • iPhone 2+ • Andriod 2+ • sessionStorage • IE 8+ • Firefox 2+ • Safari 4+ • Chrome • Opera 10.5+ • iPhone 2+ • Andriod 2+ • globalStorage • Firefox 2+ • userData • IE 5-7 • memory
  12. RALPH WHITBECK DEPENDENCY NOTE • For browsers that do not

    support JSON natively you’ll need json2.js • Unsupported browsers include: • IE 5 • IE 6 • IE 7 • Firefox 2.0 • Firefox 3.0
  13. RALPH WHITBECK USAGE amplify.store(  string  key,  mixed  value  [,  hash

     options  ]  ); • key: Identifier for the value being stored. • value: The value to store. The value can be anything that can be serialized as JSON. • [options]: A set of key/value pairs that relate to settings for storing the value.
  14. RALPH WHITBECK BASIC EXAMPLE amplify.store(  "employeeName",  "Ralph  Whitbeck"  ); var

     _name  =  request.store(  "employeeName"  );  //Ralph  Whitbeck //  ... amplify.store(  "Employee",  {  fullName      :  "Ralph  Whitbeck",                                                            startDate    :  "October  24,  2011",                                                          position      :  "Senior  Developer"  }); var  employee  =  amplify.store(  "Employee"  ); employee.fullName;    //Ralph  Whitbeck employee.startDate;  //October  24,  2011 employee.position;    //Senior  Developer
  15. RALPH WHITBECK STORE DATA EXPLICITLY //  localStorage amplify.store.localStorage(  "localVariable",  {

     foo:  "bar"  }  ); //  sessionStorage amplify.store.sessionStorage(  "sessionVariable",  {  foo:  "bar"  }  ); //  globalStorage amplify.store.globalStorage(  "globalVariable",  {  foo:  "bar"  }  ); //userData amplify.store.userData(  "userVariable",  {  foo:  "bar"  }  ); //memory amplify.store.memory(  "memoryVariable",  {  foo:  "bar"  }  );
  16. RALPH WHITBECK AMPLIFY’S REQUEST • Abstraction layer for any kind

    of request for data • Create and maintain your entire server interface and caching policy in one place by using amplify.request.define • Components that need data use amplify.request without concern for the implementation details that we defined in amplify.request.define • Requests made through amplify.request will always be made asyncronously
  17. RALPH WHITBECK USAGE - DEFINE A RESOURCE amplify.request.define(  string  resourceId,

     string  requestType  [,  hash  settings  ]  ); • resourceId: Identifier string for the resource. • requestType: Type of data retreival method from the server • [settings]: A set of key/value pairs that relate to the requestType.
  18. RALPH WHITBECK USAGE - DEFINE A RESOURCE amplify.request.define(  string  resourceId,

     string  resource  ); • resourceId: Identifier string for the resource. • resource: Function to handle requests. Receives a hash of settings. • resourceId:  Identifier string for the resource. • data: Data provided by the user. • success: Callback to invoke on success. • error: Callback to invoke on error.
  19. RALPH WHITBECK USAGE - REQUEST A RESOURCE amplify.request(  string  resourceId

     [,  hash  data  [,  function  callback  ]]  ); • resourceId: Identifier string for the resource. • [data]: A set of key/value pairs of data to be sent to the resource. • [callback]: A function to invoke if the resource is retrieved successfully.
  20. RALPH WHITBECK USAGE - REQUEST A RESOURCE amplify.request(  hash  settings

     ); • settings: A set of key/value pairs of settings for the request. • resourceId: Identifier string for the resource. • data (optional): Data associated with the request. • success (optional): Function to invoke on success.
  21. RALPH WHITBECK REQUEST DEFINITION //typically  used  for  ajax  requests amplify.request.define(

     resourceId,  type,  [  settings  ]  ); amplify.request.define(  "customers.list",  "ajax",  { url:  "/customers/", dataType:  "json" }); amplify.request.define(  "customers.update",  "ajax",  { url:  "/customers/{id}", dataType:  "json", method:  "POST" });
  22. RALPH WHITBECK REQUEST EXECUTION amplify.request(  "customers.update",  {  id:  42,  first_name:

     "Alexander" },  function(  data  )  {  ...  }); amplify.request({ resourceId:  "customers.update", data:  { id:  42,  first_name:  "Alexander" }, success:  function(  data  )  {  ...  }, error:  function(  data  )  {  ...  } });
  23. RALPH WHITBECK IN-MEMORY CACHING amplify.request.define(  "customers.list",  "ajax",  { url:  "/customers/",

    dataType:  "json", cache:  true }); amplify.request.define(  "customers.list",  "ajax",  { url:  "/customers/", dataType:  "json", cache:  30000 });
  24. RALPH WHITBECK PERSISTENT CACHING amplify.request.define(  "customers.list",  "ajax",  { url:  "/customers/",

    dataType:  "json", cache:  "persist" }); amplify.request.define(  "customers.list",  "ajax",  { url:  "/customers/", dataType:  "json", cache:  { type:  "persist", expires:  5  *  60  *  1000 } });
  25. RALPH WHITBECK CACHING REMINDERS • In-memory cache only persists for

    the length of the page load. • Navigate off or reload and the memory resets. • Persistent Caching requires amplify.store as it is used to store the data in local storage.
  26. RALPH WHITBECK MORE FLEXIBILITY • Custom Request Types • OAUTH,

    Local Database, Online/Offline • Custom Decoders • Custom Cache Types • Custom Request Definitions
  27. RALPH WHITBECK MOCKJSON • https://github.com/mennovanslooten/mockJSON • Creates fake data objects

    based on mockJSON templates. • Using variable data from a MockJSON template keeps your data unpredictable enough to catch edge cases. • Simple API for generating data
  28. RALPH WHITBECK ADDING MOCKJSON TO A MOCK var  shot_template  =

     {    //Generate  between  6  and  9  shots.      "shots|6-­‐9":  [        {            title:  "@LOREM",            url:  "#",            image_teaser_url:  "mocks/placeholder.jpg"        }    ] }; amplify.request.define(  "shots",  function(  settings  )  {    //Run  the  template  and  pass  it  to  the  success    settings.success(  $.mockJSON.generateFromTemplate(  shot_template  )  ); });
  29. RALPH WHITBECK VARIABLE REPLACEMENT • All variables in strings -

    specified as @VARIABLENAME - are auto replaced with random data from preset data stores. • Available out of the box. @NUMBER @LETTER_UPPER @LETTER_LOWER @MALE_FIRST_NAME @FEMALE_FIRST_NAME @LAST_NAME @EMAIL @DATE_YYYY @DATE_DD @DATE_MM @TIME_HH @TIME_MM @TIME_SS @LOREM @LOREM_IPSUM
  30. RALPH WHITBECK CUSTOM VARIABLE DATA $.mockJSON.data.PLACEHOLDER  =  [    “placeholder”,

       “placeholder-­‐2” ]; var  shot_template  =  {    //Generate  between  6  and  9  shots.      "shots|6-­‐9":  [        {            title:  "@LOREM",            url:  "#",            image_teaser_url:  "mocks/@PLACEHOLDER.jpg"        }    ] };
  31. RALPH WHITBECK THANK YOU • Ralph Whitbeck • Email: [email protected]

    • twitter: @RedWolves • Web: http://ralphwhitbeck.com