Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Unobtrusive Javascript and Ajax

on

  • 2,646 views

This talk discusses unobtrusive javascript an how it relates to Ajax. It introduces the UnabJah library and suggests a form for developing an unobtrusive javascript library.

This talk discusses unobtrusive javascript an how it relates to Ajax. It introduces the UnabJah library and suggests a form for developing an unobtrusive javascript library.

Statistics

Views

Total Views
2,646
Views on SlideShare
2,628
Embed Views
18

Actions

Likes
1
Downloads
19
Comments
0

3 Embeds 18

http://www.slideshare.net 12
http://dailydid.posterous.com 5
http://twtn.net 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Unobtrusive Javascript and Ajax Unobtrusive Javascript and Ajax Presentation Transcript

  • Unobtrusive Javascript And other musings
  • Like CSS? • CSS separates presentation information from the data. • CSS is delcarative. • It’s expressive and powerful. (A little CSS can eliminate tons of HTML.)
  • Which is Better? p { font-weight: bold; color:#f00; } Or <p style=”color:#f00;”> <strong>hello</strong> </p>
  • This is power!!! p { font-weight: bold; color:#f00; } • Less code. • Responds to change • Separates display from data.
  • CSS sets up an environment in which your HTML code is more powerful and meaningful.
  • More Expressive.
  • What about behavior? • What about slideshows? • What about loading ajax content? • What about those nifty little fade effects?
  • Behavior is normally defined in Javascript code.
  • These are the same. Inline Formatting <p style=”color:#f00;”> <strong>hello</strong> </p> Inline Behavior <a href=”#” onclick=”new AjaxUpdater(‘content’, ‘slide/1’)”> </a>
  • These are the same. Inline Formatting <p style=”color:#f00;”> <strong>hello</strong> </p> Inline Behavior <a href=”#” onclick=”SlideLoader.load_slide(1)”> </a>
  • Inline Formatting is bad because: • Duplicates code (extra work!) • Sprinkles display definition throughout a projects codebase (doesn’t scale) • Leads to inconsistent display definition. • Very very hard to change. • It’s just bad.
  • Inline Behavior is Bad • Duplicates code (extra work!) • Sprinkles behavior definition throughout a projects codebase (doesn’t scale) • Leads to inconsistent behavior definition. • Very very hard to change. • It’s just bad.
  • Opacity Example
  • Opacity doesn’t work well in CSS Much better as a Behavior $$(‘.faded’).each( function(el) { el.setOpacity(0.5); } );
  • This is like CSS $$(‘.faded’).each( function(el) { el.setOpacity(0.5); } ); But what happens if you update the DOM with an AJAX call?
  • This will not update the elements loaded from an Ajax call $$(‘.faded’).each( function(el) { el.setOpacity(0.5); } ); But CSS does. .faded { font-weight: bold; }
  • Wouldn’t it be cool if we cool do this in CSS: .faded { color: #fff; /* this is the cool part */ element.setOpacity(0.5); } Or even this: a.slide_link { color: #fff; /* this is the cool part */ element.observe(‘click’, function(event) { new Ajax.Updater(‘slide_area’, element.getAttribute(‘href’)); Event.stop(event); } }; }
  • Well you can’t! But how about this: UnabJah.create({ ‘.faded’: function(el) { el.setOpacity(0.5); }, ‘a.slide_link’: function(element) { element.observe(‘click’, function(event) { new Ajax.Updater(‘slide_area’, element.getAttribute(‘href’)); Event.stop(event); } }; }, ‘#flash’: function(element) { var x = function() { new Effect.Fade(element); }.delay(1); } });
  • unabjah.js • Waits until the DOM has loaded to evaluate the rules • Handles reapplication of behaviors after Ajax updates. • Won’t reapply a behavior to an element if it has already been applied • Let’s you reapply rules explicitly • Is a simple tested library that should not break unless Prototype makes major deviations from it’s documented library.
  • var UnabJah = Class.create( {   initialize: function(rules, options) {     this.options = Object.extend({scope:'default'}, options || {});     this.rules = rules || {};     this.apply_responder();     this.add_rules(this.rules);     this.add_onload_handler();   },   apply_responder: function() {     if (!this.responderApplied) {       Ajax.Responders.register({         onComplete : function() {           setTimeout(function() { this.apply_rules(); }.bind(this), 10);         }.bind(this)       });       this.responderApplied = true;     }   },   add_onload_handler: function() {     document.observe('dom:loaded', function() { this.apply_rules(); }.bind(this));   },   apply_rules: function(update_elem) {     for(var selector in this.rules)       this.apply_rule(selector, this.rules[selector], update_elem);   },   apply_rule: function(selector, func, update_elem) {     var items = update_elem ? update_elem.select(selector) : $$(selector);     items.each(function (el) {       if(!this.rule_has_been_applied(el,selector)) {         this.mark_rule(el, selector);         func(el);       }     }.bind(this));   },   mark_rule: function (el, selector) {     el[this.scope()][selector] = true;   },   rule_has_been_applied: function(el, selector) {     if(!el[this.scope()]) el[this.scope()] = {};     return el[this.scope()][selector] || false;   },   scope: function() {     return 'unabja_rules_' + this.options.scope;   },   add_rules: function(rules) {     Object.extend(this.rules, rules);   } });
  • Example
  • Present Data in HTML <div id=”slide_area”> <div class=”slide”> <h2>Slide Title</h2> <img src=”meNakedYeah.jpg”/> <a class=”slide_link” href=”/slides/2”>Next</a> </div> </div> This could still work if javascript wasn’t enabled. Graceful degradation. Plain old clean code.
  • Markup the behavior Unabjah.create({ ‘.slide_link’: function(link) { link.observe(‘click’, function(event) { new Ajax.Updater(‘slide_area’, link.getAttribute(‘href’)); Event.stop(event); }; } });
  • Refactor This is not specific to slideshows. The general pattern of binding a link to update an element is something we can easily reuse. Unabjah.create({ ‘.slide_link’: function(link) { link.observe(‘click’, function(event) { new Ajax.Updater(‘slide_area’, link.getAttribute(‘href’)); Event.stop(event); }; } });
  • Make a tool we can use later: var RemoteLink = function(update_container, link) { link.observe(‘click’, function(event) { new Ajax.Updater(update_container, link.getAttribute(‘href’)); Event.stop(event); }; }
  • Now it looks like this: Unabjah.create({ ‘.slide_link’: function(link) { RemoteLink(‘slide_area’, link); } });
  • Functional Programming RemoteLink.update = function(update_container) { return function(link) { RemoteLink(update_container, link); } }
  • This is more like it Unabjah.create({ ‘.slide_link’: RemoteLink.update(‘slide_area’) });
  • Possibilities Unabjah.create({ ‘.slide_link’: RemoteLink.update(‘slide_area’), ‘form.login’: RemoteForm.update(‘login_area’), ‘.date_field’: PopupCalendar.options({time:false}), ‘.slideshow’: Slideshow.duration(6), ‘.twitter_feed’: TwitterFeed.user(‘bhauman’), ‘.lightbox’: MyLightBox.effect(Fade) }); A set of reusable behaviors that you can declaratively define the behavior of your whole site with.
  • Rant • If you create a behavior don’t decide the unobtrusive hook for your consumers. rel=”lightbox” • Thats an obtrusive unobtrusive hook. • This requires them to change/pollute their markup. Better to let consumers select the elements from their markup as it is. • What if they change their lightbox library?
  • Process Recap • Encapsulate behavior in a function or a class • Create an bridge to that functionality that is or produces a function that takes an element • Profit
  • Unobtrusive Javascript sets up an environment in which your HTML code is more powerful and meaningful.