Posts Tagged ‘Javascript’

Error: Unable to create directory /var/www/vhosts/justswell.org/subdomains/blog/httpdocs/wp-content/uploads/2013/05. Is its parent directory writable by the server?
by admin

Even more Drag&Drop coolness between your desktop and your browser!

Posted in DD, Javascript, Swell

We are making more & more progress with the native DnD API, and being native means fully taking advantage of Event Bubbling.

In essence this means that if you want to make for example a datatable with a lot of rows without attaching events to them (remember the flyweight pattern?) you’ll only need to set your draggable element at a higher level in the hierarchy to get the DnD behavior applied on all children nodes (marked with the draggable attribute), that’s powerful and of course, reduces a lot the memory footprint of your web application.

A lot of components could benefit of this approach, Treeview, Datatable, Listview and so on.

Another part of the example shows another level of interaction between the browser and desktop, and we are sure this one will get a lot of attention and excitement!

Swell drag&drop in actionAnd the code :)

var proxyElement = html.div(null, html.span({
    'cls' : 'dd-proxy-icon'
}), html.span('Moo'));
 
 
var draggableRows = new Swell.Lib.DD.Draggable('bleh', {
    'delegate' : true,
    'proxy'  : true,
    'proxyOverride'    : proxyElement,  
    'dataCallback' : function(dt) {
        var _currentEl = this.getDragEl().current(), _stdOut = [];
 
        for(var _n = 0, _l = _currentEl.childNodes.length; _n < _l; _n++) {
            if(_currentEl.childNodes[_n].nodeType === 1) {
                var _text = $(_currentEl.childNodes[_n]).text();
                _stdOut.push(Swell.Core.trim(_text));
            }
        }
        this.setData(dt, 'text/plain', _stdOut.join("\t"));
    }
});
 
var dropTarget = new Swell.Lib.DD.Droppable('moo');
 
dropTarget.ondrop = function(e, draggable) {
    if(!!draggable) {
        draggable.getDragEl().appendTo($('moo').current().tBodies[0]);
    }
}
by

Drag and drop files from your desktop to your browser

Posted in Javascript, Swell

Since the last post, we’ve received a huge number of requests and questions about drag&dropping files onto your beloved browser.

The mechanism behind is quite simple:  the Ajax library, the DOM element wrapper and the Asset component are assuring most of the work (handling the upload and the callback process), the DDM detects the dragged files,  then your browser is doing the rest, defining the interaction between your desktop and the file input (nicely styled of course).

By now, two browsers are playing well with the demo (Safari 4, Chrome 2+)  while others degrades gracefully.

Here’s the code :

Swell.Core.Event.add('upload', 'change', function() {
    $('loader').show();
    $('foorm').xhr(function() {
        var currentEl = $('upload').current();
        $('filelist').show();
        for (var i = 0, len = currentEl.files.length; i &lt; len; i++) {
            $('filelist').appendHTML(currentEl.files.item(i).fileName + '
');
        }
        var imgs = this.responseText.split('|');
        new Swell.Core.Asset().load('img', imgs, function(img) {
            $('loader').hide();
            $(img).appendTo('image-container');
        });
    });
});

The demo:

ddimagesAnd the video:

by

Swell Widget example: ImageZoom

Posted in Javascript, Swell

As Beta release is around the corner, we are glad today to provide the first swell widget. This widgets makes intensive use of Core components and shows how much power you have at your fingertips…

This is a widget that ecommerce companies often look for, which enables to zoom on an image and view much more details than on a thumbnail, without having to display the entire image; providing better user experience.

imagezoom

Error: Unable to create directory /var/www/vhosts/justswell.org/subdomains/blog/httpdocs/wp-content/uploads/2013/05. Is its parent directory writable by the server?
by admin

Trigger image loading with Javascript and Swell

Posted in Javascript, Swell

As we are seeing growing interest for Swell, we now want to show how to use it and how cool it is :D , this is according to the milestones on our Trac a necessity and this will as well open up the project to a larger public.

One of the Core component (Lazy loader) plays well with another (Element) in this example.

playground

Enjoy!

Error: Unable to create directory /var/www/vhosts/justswell.org/subdomains/blog/httpdocs/wp-content/uploads/2013/05. Is its parent directory writable by the server?
by admin

Painless publish/subscribe system with swell’s custom events

Posted in Javascript, Swell

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

Firebug DOM

Error: Unable to create directory /var/www/vhosts/justswell.org/subdomains/blog/httpdocs/wp-content/uploads/2013/05. Is its parent directory writable by the server?
by admin

A simple yet versatile hashtable with swell

Posted in Javascript, Swell

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();
Error: Unable to create directory /var/www/vhosts/justswell.org/subdomains/blog/httpdocs/wp-content/uploads/2013/05. Is its parent directory writable by the server?
by admin

Swell makes javascript hot key event listeners a breeze…

Posted in Javascript, Swell

These days the trend is to have a seamless desktop experience in your browser, that means pushing the boundaries of the web applications by trying to mimic the natural behavior of desktop hosted solutions. One of the must-have is undoubtedly a robust and easy-to-use event toolkit. That was one of the heaviest task and probably, to date, one of the features we are most proud of.

We’ll try to make a bunch of articles on how to use the Event toolkit. Today we’ll talk about hot-keys, a hot-key is a key combination that you can use to trigger an action in your web-application, for example you are building a WYSIWYG editor and want to capture combination like Ctrl + B to turn the text in bold.

Here’s how you would create this keyboard event listener with Swell.

Swell.Core.Event.addKeyListener(document, 'ctrl+b', function(event, keys) {
 
    if(event.modifiers.ctrl) {
        if(keys.contains('b')) {
            Swell.Lib.Selection.getCurrent().wrap('<strong>$1</strong>');
        }
    }
 
}, null, null, true);
Error: Unable to create directory /var/www/vhosts/justswell.org/subdomains/blog/httpdocs/wp-content/uploads/2013/05. Is its parent directory writable by the server?
by admin

Yet another Javascript library ?!

Posted in Swell

Well, I thought it would be easier to find words for this first post ! anyways thanks for visiting this blog, we’ll try to keep you up to date on the Swell Development progress through this blog and providing as well the day to day story of our successes and failures ^^ while building a (Fully featured) javascript library.

By the way we are looking for talented developers to join the effort as there’s pretty much to accomplish (code, documentation, build tools, and so on…)

We’ll write more about our plans in the next post and will explain why there’s room for another player…