tab.js 2 KB
var $ = require('jquery'),
	util = require('./util');


var tab = function(options) {
	var defaults = {
		innerHtml: '<ul class="nav nav-pills"></ul>'
	};
	this.options = $.extend({}, defaults, options);
	$(options.el).html(this.options.innerHtml);
	this.tab = $("ul", options.el);
	this.active = undefined; //undefined==void(0)
	return this;
}
tab.prototype = {
	constructor: tab,
	init: function(data) {
		var g = this,
			p = this.options;
		$(this.tab).html("");


		var pattern = /tab=.*?(?=&&)/gi,
			tab = pattern.exec(location.hash),
			index = null;

		if (tab instanceof Array) {
			tab = tab[0];
			index = tab.split('=')[1];
		}
		g.index = index;
		this.render(data);
		g.active = index;
		p._init && p._init(g.active);
		this.bind(p.click);
		return this;
	},
	bind: function(callback) {
		var g = this,
			p = this.options;

		$(p.el).off("click", "li");
		$(p.el).on("click", "li", function() {
			$(this).addClass('active').siblings().removeClass('active');
			g.active = $(this).find("a").attr("columnname");
			g.key = $(this).find("a").attr("key");
			g.value = $(this).find("a").attr("value");

			this._init = p._init;
			callback && callback.call(this);
		});


	},
	render: function(data) {
		var g = this,
			p = this.options;

		var lis = [];
		$(p.columns).each(function(i, column) {
			var li = $("<li></li>");
			var a = $("<a href='javascript:void(0);'></a>");

			if (g.index && i == g.index) {
				li = $('<li class="active"></li>');
			} else if (!g.index && column.name == 'all') {
				li = $('<li class="active"></li>');
			}
			if (column.name) a.attr({
				columnname: column.name
			});
			if (column.key) a.attr({
				key: column.key
			});
			if (column.value) a.attr({
				value: column.value
			});

			var h_t = column.display || "";
			a.html(h_t);

			li.append(a);
			g.tab.append(li);
		});

		g.tab.html(util.__template(g.tab.html(), data || {}));

	},
	load: function(data) {
		var g = this,
			p = this.options;
		g.tab.html(util.__template(g.tab.html(), data || {}));
	}
}


module.exports = tab;