본문 바로가기

작업실

jquery.tabletree.js

(function($) {

// utility functions
function has(arr, obj) {
	for ( i in arr ) if ( arr[i] === obj ) return true;
	return false;
}

function TableTree(_this, _option) {
 
    // create shortcut variables.
    this.$thead = $(_this).find('thead');
    this.$tbody = $(_this).find('tbody');
    this.data = _option.data;
 
    // extend parameterized option
    // with default options.
    $.extend(this.option, _option);
 
    this._initialize(this.option);
 
}
 
TableTree.prototype = {
 
    option: {
		data: null,
		headers: null,
		columns: null,
        key_column: 'key',
 
        // extendable functions.
        renderKeyColumn: function(field) {
            var DEFAULT_EXPANDER= '+';
            var tdStr = '';
                tdStr += DEFAULT_EXPANDER;
                tdStr += field;
                tdStr += '';
            return tdStr;
        },
        renderColumn: function(field) {
            var tdStr = '';
                tdStr += field;
                tdStr += '';
            return tdStr;
        },
    },

	_renderHeader: function() {
		var htmlStr = '';
		for ( idx in this.option.headers ) {
			htmlStr += '';
			htmlStr += this.option.headers[idx];
			htmlStr += '';
		}
		htmlStr += '';
		console.log(htmlStr);
		$(htmlStr).appendTo(this.$thead);
	},
 
    _render: function(row) {
		var htmlStr = '';
        htmlStr += this.option.renderKeyColumn(row[this.option.key_column]);
 
        for ( key in row ) {
            if ( this.option.key_column == key ) { continue; }
			if ( this.option.columns && $.isArray(this.option.columns) && this.option.columns.indexOf(key) >= 0 ) {
	            htmlStr += this.option.renderColumn(row[key]);				
			}
        }
		
		htmlStr = '' + htmlStr + '';
		console.log(htmlStr);

        $(htmlStr)
            .find('.expander')
            .click(this._toggleFold(row[this.option.key_column]))
            .end()
            .appendTo(this.$tbody);
    },
 
    _toggleFold: function(key) {
		console.log(key);
    },
 
    _initialize: function(_option) {
        console.log('_initialize called.');
 
        // debug code
        // console.log(this.data);
        // return;
 
        $this = this;

		// if this.option.header defined, render header.
		if ( this.option.headers ) this._renderHeader();
        $.each(this.data, function(idx, row) { $this._render(row); });
    },
 
    // getOption: function(key) {
    //  return this.option[key];
    // }
 
}
 
// extending jQuery.fn with tabletree plugin.
$.fn.tabletree = function(option) {
    return new TableTree(this, option);
};
 
})(jQuery)