Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Hash object/array using jquery?

I know there is a Hash() object in the Javascript prototype framework, but is there anything in Jquery like this?

As I would like to stick with one javascript framework, rather than mixing the Prototype Frame work and the JQuery framework and use at the same time, as I worry there will be conflict and create side-effects.

So my question is: how to create Hash object/array using jquery?

Here is my function:

/* prototype framework, I want to change this to jQuery! */
var starSaves = new Hash();

function myHover(id, pos)
{
    var starStrip = $('star_strip_' + id);    
    if (starSaves.keys().indexOf(id) == -1)
    {
        var starSave = new Array();
        var imgs = starStrip.select("img")
        alert(imgs);
        for (var i = 0; i < imgs.length; i++)
        {
            starSave[starSave.length] = imgs[i].src;
            if (i < pos)
                imgs[i].src = "/images/star_1.gif";
            else
                imgs[i].src = "/images/star_0.gif";

        }
        starSaves.set(id, starSave);
    }
}
like image 664
Patrick Avatar asked Jun 09 '10 14:06

Patrick


3 Answers

There's a standalone hash table implementation called jshashtable (full disclosure: I wrote it). Using it, your code would be:

var starSaves = new Hashtable();

function myHover(id, pos)
{
    var starStrip = $('star_strip_' + id);
    if (!starSaves.containsKey(id))
    {
        var starSave = new Array();
        var imgs = starStrip.select("img")
        alert(imgs);
        for (var i = 0; i < imgs.length; i++)
        {
            starSave[starSave.length] = imgs[i].src;
            if (i < pos)
                imgs[i].src = "/images/star_1.gif";
            else
                imgs[i].src = "/images/star_0.gif";

        }
        starSaves.put(id, starSave);
    }
}
like image 69
Tim Down Avatar answered Oct 05 '22 07:10

Tim Down


A basic Hash can be achieved with basic JavaScript, not jQuery (I know that Prototype's Hash adds extra functionality, but you don't use it here).

var starSaves = {};

function myHover(id, pos)
{
    if (!starSaves.hasOwnProperty(id)) {
        var starSave = starSaves[id] = [];

        $('#star_strip_' + id + ' img').attr('src', function (index, current) {
           starSave.push(current);

           return (index < pos) ? '/images/star_1.gif' : '/images/star_0.gif';
        });        
    }
}
like image 30
Matt Avatar answered Oct 05 '22 08:10

Matt


I think you don't need jQuery for this.

var hashtable = {
    hash: {},
    exists: function(key){
       return this.hash.hasOwnProperty(key);
    },
    get: function(key){
        return this.exists(key)?this.hash[key]:null;
    },
    put: function(key, value){
        this.hash[key] = value;
    }
}
like image 27
Amadu Bah Avatar answered Oct 05 '22 06:10

Amadu Bah