Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining a function in JavaScript?

I want to make a function that add an item to my localStorage object. E.g.:

alert(localStorage.getItem('names').addItem('Bill').getItem('names'));

The first method is getItem which gets the item for localStorage objects... but addItem would be a custom function. This chain of functions would finally alert Bill.

So, how would I make this function chain to localStorage?

like image 807
Oscar Godson Avatar asked Jul 04 '10 22:07

Oscar Godson


2 Answers

This is possible if you create a wrapper/decorator object that makes chaining possible. This is how jQuery works for example. But it is useless in this case.

I made a possible implementation, though.

But getItem will break the chain (so it should always be used at the end).

storage().setItem('names', 'Bill').getItem('names'); // or
storage().setItem('names').addItem('Bill').getItem('names'); // or
storage().key('names').value('Bill').set().get('names');

Implementation

(function( window, undefined ) {

var storage = function( key, value ) {
  return new storage.init( key, value );
};

storage.init = function( key, value ) {
  this._key   = key;
  this._value = value;
};

storage.init.prototype = {

  key: function( key ) {
    this._key = key;
    return this;
  },

  value: function( value ) {
    this._value = value;
    return this;
  },

  get: function( key ) {
    key = isset(key) || this._key;
    return localStorage.getItem( key );
  },

  set: function( key, value ) {
    this._key   = key   = isset(key)   || this._key;
    this._value = value = isset(value) || this._value;
    if ( key && value ) {
      localStorage.setItem( key, value );
    }
    return this;
  },

  addItem: function( value ) {
    this._value = isset(value) || this._value;
    if ( this._key && value !== undefined ) {
      localStorage.setItem( this._key, value );
    }
    return this;
  },

  // aliases...
  getItem: function( key ) {
    return this.get( key );
  },
  setItem: function( key, value  ) {
    return this.set( key, value );
  }
};

function isset( value ) {
  return value !== undefined ? value : false;
}

window.storage = storage;

})( window );
like image 99
25 revs, 4 users 83% Avatar answered Sep 16 '22 17:09

25 revs, 4 users 83%


This is impossible.

If getItem('names') returns Bill, you can't call addItem on it.
It would be possible to add addItem and getItem methods to every item in the storage, but it would be a horrible idea.

like image 22
SLaks Avatar answered Sep 18 '22 17:09

SLaks