27
Apr 09
For an upcoming work we figured it would be useful to add JSONP support in our Asset component in order to load the given URL and once loaded, passback the JSON to a handler with the content.
What’s interesting with this approach is that we don’t rely on any hack to get the response such as evaluating all the script files in head or loading the content asynchronously then appending it.
There are numerous advantages using our solution :
- You can load the JSON from multiple sources but keep a single handler, each JSONP file processed will be passed back as an argument
- You can have a single handler for the whole sequence or listen events of each JSONP file being loaded with CustomEvents
- The tags are removed from the DOM once loaded, this avoid memleaks or JSONP collision
- This approach is robust and works equally between browsers even on old ones like MSIE 5.5
here’s a little example of what can be done:
Swell.Core.Asset.load('jsonp', [
'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=rideback&output=json&callback=',
'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=saintseiya&output=json&callback='
], function() {
for(var _n = 0; _n < arguments.length; _n++) {
var yim = arguments[_n];
for(var _i = 0, _im; _im = yim.ResultSet.Result[_i++];) {
html.img({
'src' : _im.Thumbnail.Url,
'alt' : _im.Title,
'title' : _im.Title,
'width' : _im.Thumbnail.Width,
'height': _im.Thumbnail.Height
}).appendTo('receiver');
}
}
});
No Comments , Tags: json webservices, jsonp, lazyloading
10
Apr 09
As we are preparing the upcoming release of Swell, we are actively working on a true and efficient dependency management system, and one of the key feature of the dependency manager is the ability to grab resources once the page is loaded.
Swell’s Core should be the only resource you would ever need to get started, it is not an understatement to say that we’ll lose adopters if the system is too hard to build.
Every component should be able to load its own UI definition, I mean being able to lazy load any css or image resource it needs.
Separation of concerns will help us to build a better library, that’s the way it should be, that’s the way we are !
We have looked at the various javascript lazyloading implementations on the web, some are interesting and well-minded, some others are just bloated.
Keep it simple stupid!
Our lazy loading implementation is able to load and monitor script, css and image resources, for example you want to use the Element component in your page and then want to use it when available into the global scope.
/** For a single script file without callback */
Swell.Core.Asset.load('script', 'Core/Element.js');
/** For multiple script files with a callback when all resources are loaded */
Swell.Core.Asset.load('script', ['Core/Element.js', 'Core/Hashtable.js'], function() {
$('foo').addClass('meh');
});
/** Custom event when a single file is loaded */
Swell.Core.Asset.onResourceLoaded.subscribe(function(type, res) {
if(type === 'img') {
// Do something
}
});
/** Advanced example */
var _imgs = $(document.body).getByClassName('swell-image-asset', 'img').setAttribute({'src' : 'blank.png'})
.addEvent('mouseover', function() {
this.addClass('loading');
Swell.Core.Asset.load('img', 'largeimage.jpg', function(collection) {
for(var _i = 0; _i < collection.length; _i++) {
this.setAttribute({'src' : collection[_i].src});
collection[_i] = null;
}
}, this);
}
);
Have fun !
No Comments , Tags: lazy load css, lazy load script, lazyloading, ondemand css
5
Apr 09
When using Ajax to submit a form, you’ll have to attach as args the input fields name/value combination; this task can be very boring, especially if your form takes three pages…
This is where the form serialization feature strikes, by simply specifying the form(s) name to your XHR handle, the serializer will parse through your form and assemble each content input field into an object that’ll be passed automatically to your request.
We made a choice that come very handy in our case, every serialized form is returned in a global object and once requested, “stringified”.
Why using JSON?
In some case, let’s say… in “multiples select”, we can come up with multiple values, and when using GET you’ll definitely do something like key=val, with multiple values, key[]=val, but how much server-side languages can handle this kind of GET property? not much… whereas much languages are now able to unserialize JSON.
PHP is able to “decipher” passed arrays in GET, but what about the others languages? If there’s Java/Ruby/ASP.NET folks out there, we would like to hear from you!
XHR in Element
In order to save both time and lines, it was quite interesting to think of a way to implement XHR in our Element class, take a look at these working drafts:
// well, let's say we have two forms
var forms = $('foo','bar');
// will send them separately asychronously
forms.xhr();
// this time we want to harmonize their form[method] value
forms.xhr('POST');
// or their form[action] value
forms.xhr(null, 'foo.php');
// two concurrent ajax request is somehow too much, we'd better merge them!
forms.xhr('POST', 'foo.php', true);
3 Comments , Tags: ajax, form, JSON
31
Mar 09
Handling keyboard events with Javascript is an extremely difficult task considering each browser discrepancies.
One guy compiled all the differences into a single page that he adequately called “Javascript madness : Keyboard events“, and from there you can clearly see the real madness
Of course we have directly experienced the aforementioned problems and found out pretty smart solutions for almost any browser.
The two major headaches were IE not firing keypress event on specific keys and Opera not able to prevent default behavior of keydown event.
HTMLEvents magic or how to fix messy browser implementation
The special keys encompass all the keys that don’t cause a character to appear, but execute a certain function. Among these keys we can find shift, escape, pageDown, enter and so on.
Some general caveats (courtesy of quirksmode) :
- IE doesn’t fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
- Onkeypress, Safari gives weird keyCode values in the 63200 range for delete, end, function keys, home and pageUp.Down. The onkeydown and -up values are normal.
- Alt, Cmd, Ctrl and Shift cannot be detected on Mac, except in Opera. However, you can always use the altKey, ctrlKey, and shiftKey properties.
For getting rid of this weird behavior we are capturing special keys on keydown and use a static property to hold the keyname (keymapper) and keycode that we use when keypress event is fired.
As we didn’t want to hack our code too much we just simulate the keypress event on IE when the unsupported special keys are pressed.
// Check if keypressed is a special key
_specialKeyName = this.getSpecialKeyName(e.getKeyCode());
if(_specialKeyName) {
this._specialKey = _specialKeyName;
this._keyCode = e.getKeyCode();
// This is a special key, we know that IE will not fire
// keypress event, we'll do it for him :D
if(Swell.Core.Browser.isIE) {
this.simulate(o, 'keypress');
}
}
/**
* Fires programmatically a native DOM event
* @function simulate
*
* @param {String|HTMLElement|Array} o the object to assign the handler to
* @param {String} type event type : click, change, keypress, etc, never prepend "on" keyword as Swell does this job for you
*
* @see https://developer.mozilla.org/en/DOM/element.dispatchEvent
* @see http://msdn.microsoft.com/en-us/library/ms536390(VS.85).aspx
*/
simulate : function(o, e) {
var _event;
// Testing if o is an object or a string
// add is just dealing with DOM events, and is not meant to
// handle custom events of Swell Objects
// as Swell.Core.Dom is not part of the core distribution <~20K :D
// We will use the good old document.getElementById for element retrieval
if(Swell.Core.isString(o)) {
o = _getById(o);
} else if(Swell.Core.isArray(o)) {
// Loop on function
for(var n = 0; n < o.length; n++) {
this.simulate(o[n], e);
}
o = null;
}
if(!o) {
return;
}
if(document.createEventObject) { // IE
_event = document.createEventObject();
return o.fireEvent('on' + e, _event);
}
else {
// All other browsers
_event = document.createEvent('HTMLEvents');
_event.initEvent(e, true, true); //event type,bubbling,cancellable
return !o.dispatchEvent(_event);
}
},
2 Comments , Tags: crossbrowser, key handling, keyboard events, keyboard listener
24
Mar 09
One of our objectives is to make usage of SwellJS easy in order to maximize its adoption. Usually one of the major drawbacks is the installation.
Most software you want to use on your website will require you to download it, extract it, upload it, and keep it up to date.
One of the best ways we found on SwellJS to reduce installation hassle is to remove the installation process. We will instead provide the library via a CDN.
So, what will a “CDN” do, and how does it helps to avoid installation of the SwellJS library?
Read the rest of this entry »
6 Comments , Tags: CDN, Swell, Swell Installation
20
Mar 09
Today, we are delivering the first page to play around with Swell and we are quite happy of the result. We wanted to show how easy it is to restrict the characters typed in form fields.
By using the universal selector (*) built-in Swell’s Event library, you can catch any keystroke and of course retrieve its text representation in your event handler !
Be careful the code behind the Event library is still in early Alpha stage and far from being production ready, have fun !
Restrict input chars playground page
2 Comments , Tags: block chars, restrict field input
17
Mar 09
As Element is one of the most important components, we wanted to be able to manipulate DOM, CSS and everything related to content manipulation. Our main goal is to make the user write a minimum of code while keeping the smallest codebase possible (yes, we are DRY hard fervents).
To achieve this challenging goal, we made a batch system that allows us to run a specific function without modifying it several times over given arguments.
So, to put it in a more comprehensive manner, by simply writing this snippet of code:
foo: function() {
var _fn = function(arg) {
return this.domEl.id + arg+ 'bar';
}
return _delegate.call(this, _fn, arguments);
}
If you execute $(‘foo’, ‘bar’, ‘baz’).foo(‘baz’); you’ll get ['foobazbar', 'barbazbar', 'bazbazbar'].
The _delegate method loops through the internal elements stack and executes on each element the given _fn.
getStyle at work
Another thing worth mentioning is the normalization process done backwards by getStyle, as properties may differ between browsers, which one should we choose? currentStyle or getComputedStyle? usually you would use chained if statements to address each possibility.
This is where our approach clearly gives better results by keeping trace of native properties (e.g. under currentStyle “float” would be “styleFloat”, and getComputedStyle, “cssFloat”) as well as providing an abstraction layer for getting/setting values.
var _styleExceptions = {
'CURRENT_STYLE' : {
'float' : 'styleFloat',
'opacity' : 'filter',
'border' : null
},
'DEFAULT_VIEW' : {
'float' : 'cssFloat',
'border' : null
}
};
getStyle : function() {
var _fn = function(style) {
var _method = this._domEl.currentStyle ? { o : this._domEl.currentStyle, type : 'CURRENT_STYLE' } : { o : document.defaultView.getComputedStyle(this._domEl, null), type : 'DEFAULT_VIEW' };
var _exceptions = new Swell.Core.Hashtable().inject(_styleExceptions[_method.type]);
_exceptions.defineGetter(function(key, val, arg) {
var _oStyle = arg.o,
_isCurrentStyle = (arg.type === 'CURRENT_STYLE') ? true : false;
switch(key) {
case 'opacity':
if (_isCurrentStyle) {
return /opacity\s?=\s?([0-9]+)/.exec(_oStyle[val])[1]/100;
}
case 'border':
return [_oStyle['borderTopWidth'], _oStyle['borderRightWidth'], _oStyle['borderBottomWidth'], _oStyle['borderLeftWidth']];
default:
return _oStyle[val];
}
}, _method);
if (_exceptions.exists(style)) {
return _exceptions.get(style);
}
return _method.o[style];
}
return _delegate.call(this, _fn, arguments);
}
For example retrieving the opacity value without worrying about the browser.
<div id="foo" style="filter:alpha(opacity=50);"></div>
<script type="text/javascript">
$('foo').getStyle('opacity'); // returns 0.5
</script>
No Comments , Tags: element, style
13
Mar 09
Let me start with wikipedia’s own publish/subscribe pattern definition : Publish/subscribe (or pub/sub) is an asynchronous messaging paradigm where senders (publishers) of messages are not programmed to send their messages to specific receivers (subscribers). This decoupling of publishers and subscribers can allow for greater scalability… We absolutely wanted to have this pattern implemented into Swell as we are fervent supporters of the SoC. The goal was to be able to hook the Custom event model to potentially any class as well as using custom events outside of a class context.
Custom event model
By inheriting the CustomEventModel class built-into swell, the children class is augmented with new methods and collections brought from the model. Example :
Swell.Core.Class({
name : 'Hashtable',
namespace : 'Swell.Core',
inherits : [Swell.Core.Enumerable, Swell.Core.CustomEventModel],
...
Swell.Core.Hashtable class now have those methods :
- createEvent (creates a custom event that is bound to the class ex : onHashUpdated)
- fireEvent (fires desired event and will notice all the subscribers aka execute callback functions)
- subscribe (subscribe to a custom event of the class from/outside the class)
- unsubscribe
- getEvents
In the hashtable code, we use custom events to update a static property containing the length.
var _initEvents = function() {
/**
* Initialization of the event
* @event onChange fires when an item is added/updated in the hashtable
*/
this.createEvent('onHashUpdated');
this.subscribe('onHashUpdated', _updateLength); //_updateLength is a private function of the class
}
...
/**
* Now triggering the event
*/
set : function(key, value) {
if(arguments.length === 1) {
_hash[Swell.uniqueId()] = key;
} else {
_hash[key] = value;
}
this.fireEvent('onHashUpdated', this);
return this;
},
...
Standalone custom events
This is the simplest way of using the custom event system.
In the example below we have created a basic object called button that makes use of custom events.
var button = function() {
var value = 1;
this.setValue = function(val) {
value = val;
this.onValueChange.fire();
};
this.onValueChange = new Swell.Core.CustomEvent('onValueChange');
}
var handler = function() {
alert('button value has changed');
}
var btn = new button();
btn.onValueChange.subscribe(handler);
btn.setValue('toto');
And the firebug DOM :

Firebug DOM
1 Comment , Tags: Custom event, Events, Javascript, Publish/subscribe pattern
10
Mar 09
Today we wanted to feature the hashtable object used internally by the core components and/or widgets in Swell.
At first don ‘t get me wrong, objects used as hash-tables is to date the most convenient way of storing static properties associated to a key, I just complain that it’s sometimes (not always) missing features you would find in other languages such as PHP.
Here’s the code :
Swell.Core.Class({
name : 'Hashtable',
namespace : 'Swell.Core',
inherits : [Swell.Core.Enumerable, Swell.Core.CustomEventModel],
functions : function() {
var _hash = {};
var _updateLength = function() {
var _l = 0, _n;
if(_hash.__count__) {
this.length = _hash.__count__;
} else {
for(_n in _hash) {
_l++;
}
this.length = _l;
}
}
var _initEvents = function() {
/**
* @event onChange fires when an item is added/updated in the hashtable
*/
this.createEvent('change');
this.subscribe('change', _updateLength);
}
return {
length : 0,
/**
* Constructor, initialize enumerable
*
* @function construct
* @constructor
*/
construct : function() {
this.setEnumerable(_hash);
_initEvents.call(this);
},
/**
* Resets the hashtable
*
* @function dispose
*/
empty : function() {
_hash = {};
},
/**
* Add/Update an entry in the hashtable
*
* @function set
* @param {String} key Key name
* @return {Swell.Core.Hashtable}
*/
set : function(key, value) {
if(arguments.length === 1) {
_hash[Swell.uniqueId()] = key;
} else {
_hash[key] = value;
}
this.fireEvent('change', this);
return this;
},
/**
* Add an entry in the hashtable if the key does not exist
*
* @function set
* @param {String} key Key name
* @return {Swell.Core.Hashtable}
*/
add : function(key, value) {
if(!this.exists(key)) {
this.set(key, value);
return this;
}
return false;
},
/**
* Update an entry in the hashtable if the key exists
*
* @function set
* @param {String} key Key name
* @return {Swell.Core.Hashtable}
*/
update : function(key, value) {
if(this.exists(key)) {
this.set(key, value);
return this;
}
return false;
},
/**
* Get the value of the corresponding key in the hashtable
*
* @function get
* @param {String} key Key name
* @return {Mixed/Boolean} value
*/
get : function(key) {
if(_hash.hasOwnProperty(key)) {
return _hash[key];
}
return false;
},
/**
* Exchanges all keys with their associated values in the hashtable
*
* @function flip
* @return {Swell.Core.Hashtable}
*/
flip : function() {
var _k, _tmp = {};
for( _k in _hash ) {
_tmp[_hash[_k]] = _k;
}
_hash = _tmp;
return this;
},
/**
* Returns the first item of the hashtable
*
* @function first
* @param {Boolean} [extended] Returns an array with the first item as key and second one as val (optional)
* @return {Mixed}
*/
first : function(extended) {
for(var _p in _hash) {
if(!Swell.Core.isUndefined(extended)) {
return [_p, _hash[_p]];
}
return _hash[_p];
}
return false;
},
/**
* Returns the last item of the hashtable
*
* @function last
* @param {Boolean} [extended] Returns an array with the last item as key and second one as val (optional)
* @return {Mixed}
*/
last : function(extended) {
var _lastitem = false;
for(var _p in _hash) {
_lastitem = _hash[_p];
}
if(!Swell.Core.isUndefined(extended)) {
return [_p, _lastitem];
}
return _lastitem;
},
/**
* Unsets an item from the hashtable
*
* @function remove
* @return {Swell.Core.Hashtable}
*/
remove : function(key) {
if(_hash.hasOwnProperty(key)) {
delete _hash[key];
this.fireEvent('change', this);
}
return this;
},
/**
* Applies the callback to the elements of the hashtable
*
* @function map
* @return {Swell.Core.Hashtable}
*/
map : function(fn) {
var _p, _tmp = {};
if(Swell.Core.isFunction(fn)) {
for(_p in _hash) {
_tmp[_p] = fn.call(null, _hash[_p]);
}
}
return _tmp;
},
/**
* Test if a property exists in the hash table
*
* @function exists
* @return {Boolean}
*/
exists : function(key) {
return _hash.hasOwnProperty(key);
},
/**
* Applies an user function on every member of the hashtable
*
* @function walk
* @return {Swell.Core.Hashtable}
*/
walk : function(fn) {
var _p;
if(Swell.Core.isFunction(fn)) {
for(_p in _hash) {
_hash[_p] = fn.call(null, _hash[_p]);
}
}
return this;
},
/**
* Returns an array of keys
*
* @function keys
* @return {Mixed[]} keys
*/
keys : function() {
var _k, _tmp = [];
for(_k in _hash) {
_tmp.push(_k);
}
return _tmp;
},
/**
* Pop the element off the end of array
*
* @function pop
* @return {Mixed} value of the popped item
*/
pop : function() {
var _item = this.last(true);
delete _item[0];
return _item[1];
},
/**
* Returns an array of values
*
* @function values
* @return {Mixed[]} values
*/
values : function() {
var _k, _tmp = [];
for(_k in _hash) {
_tmp.push(_hash[_k]);
}
return _tmp;
},
/**
* Returns the wrapped native object
*
* @function toObject
* @return {Object}
*/
toObject : function() {
return _hash;
},
/**
* Returns a string representation of the wrapped native object
*
* @function toSource
* @return {String}
*/
toSource : function() {
if(_hash.toSource) {
return _hash.toSource();
} else {
var _stack = [];
for(var _n in _hash) {
_stack.push('"' + _n + '" : "' + _hash[_n] + '"');
}
return '({' + _stack.join(',') + '})';
}
}
}
}()
});
But how to use it ?
A Swell class can be instantiated just like you would do with a classic object.
var ht = new Swell.Core.Hashtable();
// Put some stuff into the hashtable
ht.set('foo', 'bar');
ht.set('baz','bleh');
//Then walk every member of the hashtable to turn the value into uppercase
h.walk(function(member) {
return member.toUpperCase();
});
// Output the hash, this will give us an object like : {foo : "BAR", baz : "BLEH"}
h.toObject();
1 Comment , Tags: class, hashtable, Javascript, objects as hashtable, Swell
6
Mar 09
Here’s our thoughts about Swell’s core architecture.

Swell's Core architecture
No Comments , Tags: architecture