Category Archives: JavaScript

jQuery Communicator Singleton (Manage & Cache ajax requests)

Written by Garry Lachman (Admin). Filed under JavaScript, jQuery. Tagged , , , , , , , , , , , , , . .

Hey,
I wrote this class for cache ajax request if the same request sent twice.
The second reason why i use this class is a like there is only one exit point
from the application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var Communicator =(function(){
    var instantiated;
    var retry = new Array();
    var cached_data = new Array();

    function init (){
        return {
            dispatch:function(url, callback){
                var self = this;
                if (Communicator.getInstance().cached_data[url])    {
                    callback(Communicator.getInstance().cached_data[url]);
                    return;
                }
                if (!retry[url])    {
                    retry[url] = 0;
                }
                var _rq = $.ajax({
                    url: url,
                    timeout: 30000,
                    success: function(_data){
                        Communicator.getInstance().cached_data[url] = _data;
                        callback(_data);
                    },
                    error: function(){
                        if (retry[url] < 3) {
                            retry[url]++;
                            dispatch(url, callback, retry[url]);
                        }   else    {
                            callback("");  
                        }
                    }
                });
            },
            cached_data: {}
        }
    }

    return {
        getInstance :function(){
            if (!instantiated){
                instantiated = init();
            }
            return instantiated;
        }
    }
})()

Using the class

1
2
3
4
5
6
7
8
9
10
11
12
Communicator.getInstance().dispatch(url,function(data){
    var error = false;
    try {
            data = eval("("+data+")");
    } catch(err)    {
        error = true;
    }

    if (!error)    {
        console.log(data);
    }                    
});

Have fun :)
Garry

Share

JS: Prevent IE crash when using console (console.log)

Written by Garry Lachman (Admin). Filed under JavaScript. Tagged , , , , , , , , , , , . .

When the console is close and we call console.log from javascript most of the times
Internet Explorer will crash with the message:
Error: ‘console’ is undefined

Here is my solution for this annoying bug.

1
2
3
4
5
6
7
if (typeof console == 'undefined')   {
    var console = new Object();
    console.log = function(){}
    console.error = function(){}
    console.debug = function(){}
    console.warn = function(){}
}

Thanks “brucebannor” for advice.

Have fun :)
Garry Lachman

Share

jQuery Plugin Template

Written by Garry Lachman (Admin). Filed under JavaScript, jQuery. Tagged , , , , , , . .

Hey,
I want to share some template that i usually use for starting new jQuery Plugin.
its base template that contains public methods, private methods, settings and custom events.

And here it come..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
    (c) By Garry Lachman (http://www.garry-lachman.com), GPL License
*/


var PluginCustomEvents = {
    EVENT: "myPluginCustomEvent"
};

(function($) {
    var plugin = this;

    $.fn.pluginTemplate = function(method) {
        var methods = {
            init : function(options) {
                this.pluginTemplate.settings = $.extend({}, this.pluginTemplate.defaults, options);
                return this.each(function() {
                    var $self = $(this);
                    var self = this;
                       
                });
            }
        };

        var privateMethods = {
            privateMethod: function(){

            }
        };

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            console.error("No Method: " + method);
        }
    }

    $.fn.pluginTemplate.defaults = {
        defaultProperty: "defaultValue"
    };

    $.fn.pluginTemplate.settings = {};


})(jQuery);

Init plugin:

1
2
3
4
5
6
$("#target").pluginTemplate(); // rename it to your plugin name

// init with settings
$("#target").pluginTemplate({
    property1: "value"
});

Call public methods:

1
$("#target").pluginTemplate("method_name", "parameters");

Call private methods (inside the plugin):

1
privateMethods.privateMethod.call(this, parameters ...);

Have Fun ;)
Garry Lachman

Share

Create Classes and Object in JavaScript & jQuery

Written by Garry Lachman (Admin). Filed under JavaScript, jQuery. Tagged , , , , . .

There is few ways to create javascript object and use its as class.
In this artical i will you my favorite way to implement javascript classes.
I will combaine jQuery in this example.

First of all lets create basic object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var GarryObj = {
    init: function(options, target) {
        this.options = $.extends({}, this.options, options);
        this.$target = $(target);
        this._draw();
    },
    options:    {
        width: 100,
        height: 100,
    },
    _draw: function()   {
        this.$target.css({width: this.options.width,
                  height: this.options.height});
    }
}

We create here basic class that have 2 functions and one object to store the options.
the init class gets user options and the target (like html div).
then we merge the default options with the user options using jQuery extends function and
store the target as jQuery instance as $target.

The _draw function manipulate the target – here we build the ui by user options.

To create an instance of the class we need to add some code to the (i use to put it on js heaer file).

1
2
3
4
5
6
7
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

Now lets create a instance of our class:

We need to add target div:

1
<div id="test_div"></div>

and than

1
2
var garryTest = Object.create(GarryObj);
garryTest.init({width: 150, height: 150}, $("#test_div"));

Have fun ;)
Garry Lachman

Share

7 best jQuery charts engines

Written by Garry Lachman (Admin). Filed under JavaScript, jQuery. Tagged , , , , , . .

A chart is a graphical representation of data, in which “the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart”.[1] A chart can represent tabular numeric data, functions or some kinds of qualitative structures. [wikipedia]

List of jQuery based Charts



jqPlot

Computation and drawing of lines, axes, shadows even the grid itself is handled by pluggable “renderers”. Not only are the plot elements customizable, plugins can expand functionality of the plot too! There are plenty of hooks into the core jqPlot code allowing for custom event handlers, creation of new plot types, adding canvases to the plot, and more!



Highcharts

Highcharts is a charting library written in pure JavaScript, offering intuitive, interactive charts to your web site or web application. Highcharts currently supports line, spline, area, areaspline, column, bar, pie and scatter chart types.



GraphUp

GraphUp is a very flexible and lightweight jQuery (v1.4+) plugin to spice up your data tables. It visualizes the values using color, bar charts and bubbles.



Flot

Flot is a pure Javascript plotting library for jQuery. It produces graphical plots of arbitrary datasets on-the-fly client-side.
The focus is on simple usage (all settings are optional), attractive looks and interactive features like zooming and mouse tracking.
The plugin works with Internet Explorer 6+, Firefox 2.x+, Safari 3.0+, Opera 9.5+ and Konqueror 4.x+ with the HTML canvas tag



JS Charts

JS Charts is a JavaScript based chart generator that requires little or no coding. With JS Charts drawing charts is a simple and easy task, since you only have to use client-side scripting (i.e. performed by your web browser). No additional plugins or server modules are required. Just include our scripts, prepare your chart data in XML, JSON or JavaScript Array and your chart is ready!



PlotKit

PlotKit is a Chart and Graph Plotting Library for Javascript. It has support for HTML Canvas and also SVG via Adobe SVG Viewer and native browser support.



Emprise JavaScript Charts

EJSChart has been fully tested and verified to work properly in the following browsers. This list covers roughly 95% of browser market share



Have Fun ;)
Garry

Share

read POST variables with Javascript using PHP

Written by Garry Lachman (Admin). Filed under JavaScript, PHP + mySQL. Tagged , , , , , , . .

Hi,
Today i will show very easy way to read POST variables from Javascript using PHP.

1
2
3
<script type="text/javascript">// <![CDATA[
var post_json = "<?php echo json_encode($_POST); ?>";
// ]]></script>

We encode all POST vars with php to javascript JSON.
Now we can access the vars in simple way:

1
post_json.var_name;

Have a nice day,
Garry

Share

Custom Events in jQuery – bind & trigger

Written by Garry Lachman (Admin). Filed under JavaScript, jQuery. Tagged , , , , , , , , . .

Sometimes custom events can make the life more easy.
If you want to communicate between classes and other object on the page you can simply
trigger a custom event with data.

First of all we create data exchange div:

1
<div id="data_exchange"></div>

Now we need to listen the “data exchange” div to receive the events.

1
2
3
$('#data_exchange').bind('event_name', function(event, data) {
  alert(event + ": " + data);
});

We show alert popup when we receive the event “event_name”.

The next step is dispatch the event to the “data exchange”:

1
$('#data_exchange').trigger('event_name', 'our data');

Have a nice day ;)
Garry Lachman

Share

Factory Method Pattern in JavaScript

Written by Garry Lachman (Admin). Filed under JavaScript. Tagged , , , . .

From Wikipedia: “The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The creation of an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.”

2 Classes:

1
2
3
4
5
6
7
8
9
10
11
<script language="javascript" type="text/javascript">
// Class 1
function class_one() {
    this.init = function() {}
}

// Class 1
function class_two() {
    this.init = function() {}
}
</script>

Factory Method:

1
2
3
4
5
6
7
8
9
10
11
12
<script language="javascript" type="text/javascript">
function factory_method(){
}
// now add static function to get the instance
factory_method.get = function(_type){
    if (_type == 1) {
        return new class_one();
    } else {
        return new class_two();
    }
}
</script>

Usage:

1
2
3
4
<script language="javascript" type="text/javascript">
var _instance = factory_method.get(1);
_instance.init();
</script>

Have fun ;)

Share

Losing “this” scope in JavaScript – Solution

Written by Garry Lachman (Admin). Filed under JavaScript. Tagged , , , , , , , , , , , . .

Hi….
When using Javascript as OOP mode deep functions (function in function) lose the “this” scope.
I found some solution for this problem…
Same problem i found when you call other class with callback, the callback function returns without “this” scope.

how the problem looks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function scope_experiment() {
   
    this.test_var = "test";

    this.level_one = function() {
        alert("Level One: " + this.test_var);

        function level_two()    {
            alert("Level Two: " + this.test_var);
        }

        level_two();
    }
   
}

var test_scope = new scope_experiment();
test_scope.level_one();

The output will be:
1) Level One: test
2) Level Two: undefined

And now…. The solution:
All what you need is to pass “this” to the deep function…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function scope_experiment() {
   
    this.test_var = "test";

    this.level_one = function() {
        alert("Level One: " + this.test_var);

        function level_two(_this_scope) {
            // we use _this_scope as this
            alert("Level Two: " + _this_scope.test_var);
        }

        level_two(this); // we pass this to the function
    }
   
}

var test_scope = new scope_experiment();
test_scope.level_one();

The output will be:
1) Level One: test
2) Level Two: test

Mission Accomplished

Share