Kamis, 24 Februari 2011

[shared] javascript function with flexible parameters

for example, in ruby i can write a method like this:
def certain_method *args
  "name: " + args[0..1].join(' ') + "\noccupation: " + args[2..-1].join(' ')

certain_method 'aya', 'hirano', 'the', 'best', 'seiyuu', 'in', 'the', 'world'
# -> "name: aya hirano\noccupation: the best seiyuu in the world"

but how to do it in javascript?

we can use function's arguments for that.
arguments object is a local variable within all functions.

You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as: arguments[0], arguments[1], arguments[2]

more detailed article can be seen here:

ok, now for the above ruby method, the js function with equal behavior should be something like this:
function certainMethod(like, usual, you, can, define, any, parameters, here) {
    var argsArr = $(arguments).get(); // convert arguments to array
    return 'name: ' + argsArr.slice(0, 2).join(' ') + "\noccupation: " + argsArr.slice(2).join(' ');
    // first params (like) equal with arguments[0]


[shared] rounding closer to zero in javascript

dengan menggunakan double bitwise not operator (~~)
var a = 1.9;
var b = -1.8;
var c = '-2.8';
var d = 'string';
var e = document;
~~a; // -> 1
~~b; // -> -1
~~c; // -> -2
~~d; // -> 0
~~e; // -> 0

operator ~~ lebih cepat dari Math.floor atau Math.ceil jadi bisa menjadi alternatif 2 fungsi tersebut..


Kamis, 17 Februari 2011

[shared] javascript deleteIf method

Background story

Di suatu project saia membutuhkan selector jquery spesial yg dapat memfilter data dari suatu element, misalkan saia ingin mengambil semua element dengan class "certain_class" dan mempunyai tooltip (menggunakan jquery.qtip) yg dapat diketahui dari adanya elem.data('qtip').

Tetapi selector data tidak dapat dilakukan (paling tidak saia tidak tahu bagaimana melakukannya), karena itu saia memutuskan untuk membuat method deleteIf untuk array dengan meniru konsep delete_if ruby.

Menggunakan method deleteIf untuk membuang element2 yg tidak mempunyai tooltip, contoh kasus diatas dapat dilakukan dengan:
$('.certain_class').deleteIf(function(){return !$(this).data('qtip');});


  deleteIf: function(fn){
    return $(this.get().deleteIf(fn));

$.extend(Array.prototype, {
  deleteIf: function(fn){
    var newArr = [];
    for(var i=0; i < this.length; i++){
      if(!fn.call(this[i], i)) newArr.push(this[i]);
    return newArr;


Method deleteIf yg pertama hanya merupakan shortcut untuk melakukan deleteIf pada jQuery object, intinya hanya merubah jQuery object menjadi Array object dengan method get() kemudian memanggil deleteIf milik Array dan merubah hasilnya kembali menjadi jQuery object.

Method deleteIf di array cukup simple, hanya meng-iterasi array dan memanggil fungsi yg di-passing dengan object yg diiterasi dan mem-push object tersebut ke array baru bila fungsi mengembalikan nilai false.

Kedua method deleteIf ini merupakan bagian dari jquery.extended_helper versi 2.5 (saat ini masi dalam pengerjaan, dan mungkin berubah sewaktu2)


Rabu, 09 Februari 2011

jsfiddle a great way to share your js code


I'll also add some demo in several of my posts about js.

Post with demo included (will be updated):
- http://tech.maysora.com/2011/02/identify-object-type-in-javascript.html

jquery programming and jquery plugin authoring commandments

jQuery Commandments

You shall not instantiate more than one jQuery object containing the same set of nodes.,

You shall not re-query the DOM for a given selection at any time unless it is suspected that the returned collection will have changed since the last query.,

You shall place scripts dependent on the readiness of the DOM at the bottom of the document.,

You shall favor CSS3 selectors over jQuery's psuedo-classes and special filters.,

You shall not use browser detection or browser inference.,

You shall use the correct spelling of jQuery and honour the capitalisation of its Q in any correspondence relating to it.,

You shall isolate any issues you have before posting to IRC or a forum, and especially before opening a ticket in the bug tracker.,

You shall, when requiring a reference to a DOM node created by yourself, gain that reference prior to DOM injection.,

You shall favor event delegation when the event in question propagates and when there are a substantial number of elements to be bound to.,

You shall not use jQuery when a faster and terser solution exists in the native DOM API.

jQuery Plugin Authoring Commandments

You shall return a jQuery object unless the method is intended to return something else.,

You shall return the instance on which the method is being called unless you wish to mutate the collection, in which case you should use the pushStack method to return a new jQuery instance.,

You shall make configuration accessible under the plugin's namespace.,

You shall make it possible to override the configuration on a per-call basis.,

You shall not use the globally defined dollar identifier.,

You shall not pollute namespaces unrelated to the plugin.,

You shall namespace any events binded to by the plugin.,

You shall remember that one configurable callback function is better than ten specific configuration options.,

You shall document the plugin.,

You shall respond gracefully should a jQuery instance contain no elements.

source: https://github.com/jamespadolsey/jQuery-Commandments

Selasa, 01 Februari 2011

[shared] identify object type in javascript

UPDATE: i changed the function name to $.typeOf(obj) to prevent ambiguity with css className, please use extendedhelper 2.4b or later

untuk sebagian besar object kita dapat menggunakan typeof, contoh:
typeof object; // will return object class name in string

tetapi untuk bbrp object seperti Array, Date, window, document dll, typeof akan mengembalikan "object" bukan class yg seharusnya, untuk mengakalinya kita dapat menggunakan Object.constructor, contoh fungsi lengkapnya:

$.getClassName = function(obj){
    var constructorStr = obj.constructor.toString();
    var tempMatch = constructorStr.match(/function (.+)\(/);
    if(!tempMatch || tempMatch.length != 2) tempMatch = constructorStr.match(/ (.+)\]/);
    return tempMatch[1];
    return (typeof obj).capitalize();

$.getClassName(1); // -> 'Number'
$.getClassName('Aya Hirano'); // -> 'String'
$.getClassName(['A','H']); // -> 'Array'
$.getClassName(null); // -> 'Object'
$.getClassName(undefined); // -> 'Undefined'
$.getClassName(new Date); // -> 'Date'
$.getClassName({'aya':'forever'}); // -> 'Object'
$.getClassName(document); // -> 'HTMLDocument'
$.getClassName(window); // -> 'Window'
$.getClassName(document.getElementsByTagName); // -> 'Function'
$.getClassName(document.getElementsByTagName('div')[0]); // -> 'HTMLDivElement'

fungsi getClassName tersebut ada di jquery.extended_helper 2.4 dan menggunakan fungsi capitalize dari js tersebut.


Combining jquery fullcalendar with jquery qtip

buat ntar aj lah.. lg males..