» tagged pages
» logout

sorted by: recent | see : popular
Content Tagged with front + JavaScript

Ejacs: Why you would want to a JS runtime in Emacs Lisp

I had to hold this back until Friday, because you will need some time to read Steve Yegge talking about his new project Ejacs:

Ejacs is an Ecma-262 compliant JavaScript interpreter written entirely in Emacs Lisp. It should work in GNU Emacs versions 22 and higher.

The parser and evaluator are ports of Brendan Eich’s Narcissus (JavaScript in JavaScript). The runtime is my own implementation, with a few exceptions (notably the regular expression engine) that are ports of Mozilla Rhino code.

The post is true Steve-y. He rambles and loops in the way that Billy Connolly does in a standup routine, somehow managing to hold on to enough string to get his way back. Take some time to read the beast in full, but here is my translation:

  • Steve talks about playing guitar
  • He then mentions Ejacs
  • He talks about Narcissus the cheater
  • Reading the ECMA-262 specification is a lot of fun
  • Holy crap he had to learn a lot of elisp
  • Emacs has arbitrary-precision mathematics, deep Unicode support, rich Date and Calendar support, and an extensive, fairly complete operating system interface.
  • All that for a “text editor” huh. Oh, it is a platform.
  • js2-mode came first
  • Rewrite it by porting Mozilla Rhino’s parser, which is (only) about 2500 lines of Java code. Ejacs is something like 12,000 lines of Emacs-Lisp code, all told, so that didn’t seem like a big deal.
  • JavaScript is better than elisp? Blashphemous
  • Problem #1: Momentum
  • Problem #2: No encapsulation
  • Problem #3: No delegation
  • Problem #4: Properties
  • Problem #5: No polymorphic toString
  • Emacs advantages: Macros and S-expressions
  • That said, I suspect I would probably prefer Clojure over Rhino, if I ever get a chance to sit down with the durn thing and use it, so it’s not so much “JavaScript vs. Lisp” as it is vs. Emacs Lisp.

Ajax: Ajaxian

Timing in JavaScript and browsers can’t be trusted

This is officially the week of John. If he delivers top notch posts for the rest of the week he wins an Ajaxian award or something. Maybe we need to bring back the "pack of cards" where each card is an Ajax personality and John gets to be Ace of Hearts or something.

I remember talking with some of the V8 team about how poor the world of timing is. Chrome is a lot more accurate in its timing, which can do it a disservice in browser performance tests. Some browsers would respond with "0" when Chrome would return "0.001" and it would hence suffer.

Add that to the flawed "just add up the total time for all tests" mentality of some tests and you end up with very skewed results (you could do amazingly bad on one test that in practice never matters and really well on the others, but it all evens out).

Here comes John with a post on the accuracy of JavaScript timing which came out of a bad situation:

I was running some performance tests, on Internet Explorer, in the SlickSpeed selector test suite and noticed the result times drastically fluctuating. When trying to figure out if changes that you've made are beneficial, or not, it's incredibly difficult to have the times constantly shifting by 15 - 60ms every page reload.

This lead him to tests life on various browsers and operating systems and he put up the raw data for you to check out.

He concludes:

Testing JavaScript performance on Windows XP and Vista is a crapshoot, at best. With the system times constantly being rounded down to the last queried time (each about 15ms apart) the quality of performance results is seriously compromised. Dramatically improved performance test suites are going to be needed in order to filter out these impurities, going forward.

Ajax: Ajaxian

Guid0: JavaScript GUIDs

Our own Michael Mahemoff is at it again, creating a simple little GUID generator called Guid0:

Guid0 is a GUID library for Javascript. Okay, it doesn't yet do official, bona fide, 128-bit, GUIDs yet, mainly for API design reasons. But this is a library you might find useful if you want to generate a unique ID in your Ajax app.

JAVASCRIPT:
  1.  
  2. // simple
  3. guid = new Guid();
  4. var newguid = guid.generate();
  5.  
  6. // options
  7. guid = new Guid(
  8.   {
  9.         chars: Guid.constants.base85// or you could say "abc" if you only wanted those chars to appear
  10.         epoch: "June 1, 2003",
  11.         counterSequenceLength: 2, // a counter field appended to the end
  12.         randomSequenceLength: 2 // a random field appended to the end
  13.   }
  14. );
  15.  

He is working on 128-bit support.

Ajax: Ajaxian

Trying to be private in JavaScript

Erik Arvidsson has an updated take on instance private, class private, package and friends.

One thing that shoots out at you is actually at the end:

Gmail was written without any true private members. We just use a naming convention.

We love to focus on little geek things like encapsulation, but once again... you can write amazing, complex applications without purity.

In his post, Erik talks about the various issues around getting privacy and how closure magic can be "very memory hungry since every instance needs its own function to encapsulate the local vars."

He then walks through ideas on getting the best of both worlds (private but performant) and ends up with a version you can try that even allows you C++ "friends" semantics:

JAVASCRIPT:
  1.  
  2. var A;
  3. (function() {
  4.   var KEY = {};
  5.   A = ...;
  6.  
  7.   var friendKeys = {};
  8.   A.addFriend = function(id, key) {
  9.     friendKeys[id] = key;
  10.   };
  11.  
  12.   function getFriendPrivate(obj, id) {
  13.     return obj._getPrivateWithKey(friendKeys[id]);
  14.   }
  15.  
  16.   A.prototype.accessFriendPrivate = function(obj) {
  17.     return getFriendPrivate(obj).b;
  18.   };
  19. })();
  20.  
  21. var B;
  22. (function() {
  23.   var KEY = {};
  24.   B = ...;
  25.   A.addFriend('B', KEY);
  26. })();
  27.  

Yet, after all that, he still doesn't think you should use it :)

Ajax: Ajaxian

Reglib and jQuery Demo

We posted on reglib, the new declarative event based library by Greg Reimer. I was a little confused at first, but Greg has posted a follow up which includes a demonstration comparing reglib to jQuery that makes his strategy a lot clearer:

Let me first of all stress that I'm not trying to bust on JQuery here. JQuery does something that needs to be done, and it does it just about as well as can be done given the tool-set browsers have collectively placed at our disposal.

With that said, I'm going to go ahead and pimp the reglib way of doing things, by which I mean declarative, over the load-traverse-modify methodology, which JQuery makes so easy.

The demo page linked below has two identical interactive widgets; one wired up using JQuery, and the other wired up using reglib.

The page is rigged like a science experiment, with a control followed by several tests in which you observe differences in behavior between the two widgets in response to various stimuli. The goal is to demonstrate reglib's resilience under duress (as it were). Enjoy.

The tests show:

The JQuery widget has been cloned using the DOM clone() method. After closing this message, note how the cloned version is non-functional. This is because event behavior needs to be explicitly re-added to each new element under the load-traverse-modify methodology.

The reglib widget has been cloned using the DOM clone() method. After closing this message, note how the cloned version functions normally since reglib event declarations automatically affect all additions to the DOM.

The DOM has been completely overwritten by: document.body.innerHTML += ''; After closing this message, note how none of the JQuery widgets work anymore, meanwhile the reglib widgets continue to function as normal.

At the end of this page's HTML source is a comment containing a huge block of random numbers. If you don't have a fast internet connection and you SHIFT+RELOAD this page, it will simulate network latency and/or or dynamic page processing delays, which cause a delay before the load event fires. After closing this message, SHIFT+RELOAD the page. While the page is yellow it means the load event hasn't fired. During this time, note how the JQuery widget is non-functional, but the reglib widget is functional. This may not be apparent if you have a fast internet connection.

Ajax: Ajaxian

Detect Ajax Framework with WTFramework

Because viewing the source is too bothersome, we now have WTFramework (short for "What The Framework", obviously), a bookmarklet that will detect and display the Ajax / JavaScript frameworks used in the current website.

It does so by checking for loaded JavaScript objects for each framework, not by analyzing the <script> element URIs.

Handy.

Ajax: Ajaxian

JavaScript Graph Plotting Tool

We've seen the community do a lot with <canvas> over the past few months, and every so often it's fun to see the good ol' <div> approach to graphics and animation.

Tavs Dokkedahl gives us a good one of those with his JavaScript Graph Plotting Tool:

As part of a larger animation framework I have created a plotting tool for
visualizing functions. It is made entirely in JavaScript, uses no graphics
and the generated source code is W3C compliant.

The first beta is ready for public viewing (and hopefully feedback) and
currently supports

Real valued functions of one variable y = f(x)
Parameter functions for plane curves (x,y) = f(t)
Customizable plots like curve resolution and axis positioning.
Simple zoom functionality (not for plane curves)

It's actually a pretty cool little cross-browser app.

Ajax: Ajaxian

Weed Out Obtrusive JavaScript

By now, most developers have (or should have) come to realize how important it is to build unobtrusive JavaScript code. Apart from ensuring a better user experience, today's tools and libraries make it extremely easier to embrace this practice.

Continuing down the path of providing developers good tools, Robert Nyman of DOMAssistant fame has updated his Obtrusive JavaScript Checker. The tool comes in a couple of different forms including a GreaseMonkey script, a Firefox add-on and newly included, a command for use with Mozilla's Ubiquity Firefox add-on.

One common and tedious task when improving code is to find inline events in the HTML code, and make sure they are implemented in an unobtrusive fashion instead (more about unobtrusive JavaScript). The web is riddled with inline events, and I strive to make it a better place. :-)

The Obtrusive JavaScript Checker tool traverses through all elements in a web page, and when it finds a HTML element with inline events, it highlights it with a red border. The newest release now offers support for "javascript:" links as well as much greater detail about the element when you hover over it. In addition, a new report summarizes the number of javascript: links and inline events in the current web page as well as the number of occurrences of each type of inline event.

Link to Robert's updated Firefox add-on: https://addons.mozilla.org/en-US/firefox/addon/9505

Ajax: Ajaxian

Widgetplus: Server side Ajax widgets

Mikael Bergkvist has created Widgetplus, a gadget platform. He told us about it.

XML Runtime

The structure of an application is defined in XML.

It’s loaded into the serverside runtime like this: javascript:xin.app(' http://www.naltabyte.se/desktop/xin/demo/programs/basics.xml ');

We get this as a result. (the ‘test this’ link)

Changes to the app remain persistent because on the server, the xml object has changed.

Of course, different users gets different versions of the same widget, because they have their own xml runtimes.

A widget can contain any amount of javascript to execute clientside, and also include any css to style it, like this calendar application.

A widget can also split itself into subsets, this example opens a new widget as a dialog, which is really a part of the same widget, and saves data back to itself from it.

XML objects can access each other on the server within the boundaries of the same account.

It means that widgets can access other widgets and send/recieve data from them.

Data can also be sent / retrieved cross domain, without opening the widget on the client at all.

The xml for this app in this example, which is behaving much like a webservice, is here.

File system access

Widgetplus allows complete filesystem access for a widget, but only within the user account.

By default, widgets always access the demo account, but when logged in, they access the users home account, it’s files and folders, and other settings.

This is crossdomain by default, like this example on Blogger, which accesses all files on the demo account.

There are several more ways this can play out:

The API lets anyone build their own solutions/variations of this.

Conclusion

These two parts, together, define what widgetplus is.

It’s a serverside xml runtime for widgets, which can access and manipulate files and folders that belong to the free user account.

Users can always sign up / log in to any widget (by default), the developer wont have to bother about that.

Widgetplus clones all widgets as soon as someone signs up, and also automatically creates a webspace directory for the new user with the default folders in place.

Otherwise, whenever someone logs in, it simply serves the requested xml object(s) associated with that user.

It’s important to note that widgetplus isn’t a BOX.net service, the webspace is for widgets - and whatever they do with it – it’s not for uploading your entire music collection. We will move to a server network in about two months, after which we plan to offer unlimited file storage, but for now, we need to keep a tight leach.

Ajax: Ajaxian

How to structure your JavaScript code

Peter Michaux has shared how he structures his code these days, as he has settled on a pattern:

The code example below is a simple little logger widget. It appends messages to a list and has a clear link to delete all the recorded messages.

JAVASCRIPT:
  1.  
  2. // Wrap code with module pattern.
  3. (function() {
  4.   var global = this;
  5.  
  6.   // helper functions
  7.   var sanatize = function(msg) {
  8.     return (String(msg)).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
  9.   };
  10.  
  11.   // widget constructor function
  12.   global.MY_makeLogger = function() {
  13.  
  14.     // private instance methods   
  15.     var clear = function() {
  16.       LIB_emptyElement(logEl);
  17.     };
  18.     var append = function(msg, className) {
  19.       LIB_insertBottom(logEl,
  20.         '<dt class="'+className+'">' + (new Date()) + '</dt>' +
  21.         '<dd class="'+className+'">' + sanatize(msg) + '</dd>');
  22.     };
  23.  
  24.     // create widget DOM fragment
  25.     var parser = document.createElement('div');
  26.     LIB_upateElement(parser,
  27.       '<div class="Logger">' +
  28.         '<p><a href="#" class="clearLink">clear</a></p>' +
  29.         '<dl class="log"></dl>' +
  30.       '</div>');
  31.  
  32.     // find pieces and enliven DOM fragment
  33.     var rootEl = LIB_find('.Logger', parser)[0];
  34.     parser = null; // enable garbage collection of parser div
  35.     var logEl = LIB_find('.log', rootEl)[0];
  36.     LIB_on(LIB_find('.clearLink', rootEl), 'click', function(e) {
  37.         LIB_preventDefault(e);
  38.         clear();
  39.     });
  40.  
  41.     // public instance methods
  42.     return {
  43.       getRootEl: function() {return rootEl;},
  44.       log      : function(msg) {append(msg, 'log'  );},
  45.       warn     : function(msg) {append(msg, 'warn' );},
  46.       error    : function(msg) {append(msg, 'error');}
  47.     };
  48.  
  49.   };
  50. })();
  51.  

He talks about how he uses naming conventions to keep track of library functions, exported functions, gensym ids.

Ajax: Ajaxian

Delaying JavaScript Execution

Matt has a nice post on delaying JavaScript execution in a way that waits for certain events to finish:

If you're looking to execute javascript code whenever someone finishes (or stops temporary) scrolling, moving the mouse, or resizing the page, you may find the following segment of code useful.

He shares the following boilerplate code:

JAVASCRIPT:
  1.  
  2. var onFooEndFunc = function() {
  3.         var delay = 50; /* milliseconds - vary as desired */
  4.         var executionTimer;
  5.        
  6.         return function() {
  7.                 if (executionTimer) {
  8.                         clearTimeout(executionTimer);
  9.                 }
  10.        
  11.                 executionTimer = setTimeout(function() {
  12.                         // YOUR CODE HERE
  13.                 }, delay);
  14.         };
  15. }();
  16.  

This can be useful in a variety of ways, but it got me thinking about having the ability to download code lazily. For example, a friend shared information on an app that would wait for a click and then download code to run that functionality. This was bad, as it made it seem very slow indeed. Instead, the code could be split up into core (what has to be loaded as soon as possible) and then load other code when idly using this technique.

Ajax: Ajaxian

Fronteers Conference Videos Available on the YDN Theater

The Fronteers conference recently held in Amsterdam featured a bevvy of top shelf speakers. Developers such as Dean Edwards, Stuart Langridge, Chris Heilmann and Tom Occhino, among others, discussed JavaScript, CSS, accessibility issues and more.

Yahoo!, via the Yahoo! Developer Network, is hosting several videos from the conference and it's definitely worth a visit to see these prominent speakers in action.

Ajax: Ajaxian

Form.Check: Great Form Validation for MooTools

Form validation is one of those problems that every IT developer has to deal with at one point or another. Form.Check is a MooTools plug-in library for dealing with client-side validation easily:

And, it's very easy to use:

JAVASCRIPT:
  1.  
  2. window.addEvent('domready', function(){
  3.         new FormCheck('formular', {
  4.                 display : {
  5.                         errorsLocation : 1,
  6.                         indicateErrors : 2
  7.                 }
  8.         })
  9. });
  10.  

Ajax: Ajaxian

Fixing Loss of Focus on IE

Continuing with SitePen stories for today, Dustin Machi posted a short but interesting piece on how to detect loss of focus on IE6.

So your cool new app is perfect, but you want it to lock the user out when the browser hasn’t had focus after 15 minutes? Well that’s easy you think, I’ll just connect to the document’s blur and focus events and be good to go. You quickly add a little bit of code to your Dojo widget:

JAVASCRIPT:
  1.  
  2. dojo.connect(dojo.doc, "onblur", this, "onWindowBlur");
  3. dojo.connect(dojo.doc, "onfocus", this, "onWindowFocus");
  4.  

After reluctantly firing up your Virtual Machine to test Internet Explorer 6, much to your dismay, onfocus events are immediately followed by onfocusout events. You feel the harsh reality that IE6 is going to suck away a bit more of your life.

Fortunately, while the solution seems to be difficult to track down on the “interwebs”, it is in fact pretty simple. The key is to understand that IE tracks the activeElement (document.activeElement) and fires onfocus and onfocusout events as the activeElement changes. As the onfocusout events occur, you must track what the activeElement is. When an onfocusout event happens and the activeElement doesn’t change, then the window has lost focus.

Here's the final cross-browser version:

JAVASCRIPT:
  1.  
  2. if (dojo.isIE) {
  3.    dojo.connect(dojo.global, "onfocus", this, "onWindowFocus");
  4.         dojo.connect(dojo.doc, "onfocusout", this, function() {
  5.              if (this._activeElement != document.activeElement){
  6.                     this._activeElement = document.activeElement;
  7.              }else{
  8.                     this.onWindowBlur()
  9.              }
  10.         });
  11.  }else{
  12.     dojo.connect(dojo.doc, "onblur", this, "onWindowBlur");
  13.     dojo.connect(dojo.doc, "onfocus", this, "onWindowFocus");
  14.  }
  15.  

Ajax: Ajaxian

Reinhardt: Client-side URL Dispatching from SitePen

Kevin Dangoor from SitePen recently announced the release of a small pet project: Reinhardt. From the blog:

A typical server-side web framework today includes three main components: a URL dispatching to some controller object scheme, a template engine, and a data mapping facility. Currently in Dojo, you’ll find that the latter two items already exist. dojox.dtl provides the first one, and dojo.data provides the second.

Given that Dojo already offers an implementation of the Django template engine, and that regular expression-based URL dispatch was a good fit for our problem at hand, I decided to [create a] URL dispatch on the model provided by Django.

Reinhardt is the name I gave to this client-side web framework.

Using Reinhardt, you pair regular expressions to method calls:

JAVASCRIPT:
  1. var patterns = reinhardt.urldispatch.patterns("demo.code",
  2.   [/^list\/(\d*)$/, "showMovieList", ["year"]],
  3.   [/^search$/, "search"],
  4. );

(The first argument to the patterns function provides the URL prefix required for Reinhardt to dispatch a URL.)

Hacking Support for Groups

Because JavaScript regular expressions don't support named groups, you can pass in a group name as a third parameter:

JAVASCRIPT:
  1. [/^movie\/(\d+)\/$/, "whatyear", ['id']],
  2. [/^movie\/([\w ]+)\/$/, "whatyear", ["name"]],

Kevin explains further about this feature:

These two entries show that the patterns are matched in order. movie/10/ would match both of the expressions. But, movie/Cars/ will only match the second. If the first one is a match, demo.code.whatyear is called with an ‘id’ attribute on the parameters object. If the second matches, there will be a ‘name’ attribute passed to that same function.

Kevin imagines a future where this hack could go away:

JavaScript regular expressions do not support named groups as Python’s do. Adding named groups would likely be a fairly simple extension to the syntax, but is not something that I’ve done. At some point in the future, there may be the option to pass in a string that can include named groups rather than just a standard regex object. Similarly, since Reinhardt does not do any parsing of regular expressions, it has no way of putting values back into a URL pattern to generate a URL.

Not Quite a Project Yet

At this point, it simply offers URL dispatch. I can imagine a client-side framework offering tools to help you organize large Dojo-based applications in easy to understand, simple to grow manner. The built-in URL dispatch could also provide automatic history and back button support. For now, however, it is just a small bit of code to make client-side URL dispatch clean and simple.

I should note at this point that Reinhardt is more of a demo than a real open source project. However, it is a straightforward implementation and includes unit tests, so you can confidently use it for real URL dispatch work.

Ajax: Ajaxian

Peppy: New CSS 3 selector engine

James Donaghue has released Peppy, the first release of his CSS 3 compliant selector engine that runs independent of one particular library (and can thus be used with any of them).

He has some bold claims on speed:

As it stands now Peppy is faster1 than all other major JavaScript libraries with DOM querying capabilities (Prototype 1.6.0.3, JQuery 1.2.6, MooTools 1.2.1, EXT 2.2, DoJo 1.2.0, YUI 2.6.0). It is faster2 than Sizzle by John Resig and it also is cross browser (IE included). Take a look for yourselves, I have a profiling page set up here.

At 10k it is an ideal replacement for other excellent but bulkier libraries (whose feature sets span beyond DOM querying) when features additional to DOM querying are not needed in your web application. If you are designing your own JavaScript library or want to replace your existing libraries selector engine then Peppy is an ideal candidate.

Comments, both positive and negative, are most welcomed and desired. I want to improve this thing! Please take a look here.

John Resig has also discussed a new selector engine that he is working on that is performing very well, and there has been much talk about having engines that can be shared resources for the Ajax libraries.

Ajax: Ajaxian

Great JavaScript and CSS Menu Libraries

Noupe is doing a good job cataloging content, such as their post on great JavaScript CSS menu libraries which features:

  • Sexy Sliding Menu - Andrew Sellick decided to use mootools due to the smoothness of their effects, however, he developed a sliding menu using script.aculo.us
  • FastFind Menu Script - This script allows for nested menus, based on dynamic "AJAX" responses. The menu can also be dragged/dropped thanks to the jQuery Interface Library.
  • Webber 2.0 Dock Menu - Great example of a dock type navigation.
  • Phatfusion- Image Menu - Image menu using javascript, onClick event keeps selected item open and to close it again.
  • Drag and Drop ordering in a TreePanel - This example shows basic drag and drop node moving in a tree. In this implementation there are no restrictions and anything can be dropped anywhere except appending to nodes marked "leaf" (the files).
  • Custom Menu Events This is a combination of animation and custom events where Think Vitamin team show us how menu items sliding into view and firing off subscribable events using Yahoo! UI
  • Context Menu Functionality This is a combination of animation and custom events where Think Vitamin team show us how menu items sliding into view and firing off subscribable events using Yahoo! UI.
  • LavaLamp jQuery Sliding Menu It is a jQuery sliding nifty effect menu with light weight code and extra two more interface styles.
  • Slashdot Menu- Dynamic DriveThis is a stylish collapsible menu modelled after the navigational menu found on Slashdot.
  • Mootools menu with Accordeon and EffectsThis cool menu has a neat effect by hovering over the links, and opens a 2 level submenu with an accordeon.
  • CSS Dock Menu If you are a big Mac fan, you will love this CSS dock menu that Nick La designed. It is using Jquery Javascript library and Fisheye component from Interface and some of their icons.
  • jQuery Plugin: Sliding Menu A very simple sliding menu using the effects provided by the Interface plugin.
  • Accessible expanding and collapsing menu

Ajax: Ajaxian

Ajaxian Featured Tutorial: Building a JavaScript table grid application with TaffyDB

Back in March, we posted about Ian Smith's newest project, TaffyDB, the lightweight JavaScript library that acts as thin data layer inside Web 2.0 and Ajax applications.

Ian contacted us to let us know about a new tutorial that he posted which provides step-by-step instructions on how to best implement TaffyDB:

TaffyDB extracts the "hard part" of working with data in JavaScript. It provides methods to insert, update, remove, sort, and filter a data collection in much the same way you can with SQL. But how do you take advantage of this when building a data intensive application? How can you incorporate what TaffyDB does well to minimize and simplify your code?

In this tutorial you'll go step by step and build a simple data grid application that uses TaffyDB as the engine. The application will render a table and expose options to customize the table to your liking.

In this tutorial, he runs you through important TaffyDB steps such as initializing a grid, adding custom columns, implenting column sorting and more.

If you've not checked out TaffyDB, this tutorial is a great way to get acquainted with it.

Ajax: Ajaxian

Another look at JavaScript inheritance

Stoyan Stefanov of Yahoo! has published a nice article on JavaScript's class-less objects.

This is published on JavaRanch, so it talks to the Java community, and uses that lense to explain the differences.

He delves into:

  • Constructor functions
  • Function objects and prototype property
  • Inheritance via the prototype
  • Inheritance by copying properties
  • Crockford's beget object:
    JAVASCRIPT:
    1.  
    2. function begetObject(o) {
    3.   function F() {}
    4.   F.prototype = o;
    5.   return new F();
    6. }
    7.