tab2.js 1.41 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);
	return this;
}
tab.prototype={
	constructor: tab,
	init:function(data){
		var g = this,
			p = this.options;
		g.data=data;
		var pattern = /tab=.*?(?=&&)/gi,
			tab = pattern.exec(location.hash),
			index = null;

		if (tab instanceof Array) {
			tab = tab[0];
			index = tab.split('=')[1];
		}
		this.render();
		this.bind();
		return this;
	},
	render: function() {
		var g = this,
			p = this.options;
		$(this.tab).html("");
		$(p.columns).each(function(i, column) {
			var li = $("<li></li>");
			if(i==p.active){
				li = $("<li class='active'></li>");
			}
			var a = $("<a href='javascript:void(0);'></a>");
			var display=util.__template(column.display,g.data);
			a.html(display);

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

		});
		g.tab.html(g.tab.html());
	},
	bind:function(){
		var g = this,
			p = this.options;
		$(p.el).on("click", "li",function(){
			p.active=$(this).index();
			p.click && p.click.call(this);
			g.render();
			return false;
		});
	},
	setData:function(data){
		var g = this,
			p = this.options;
		g.data=data;
	},
	getData:function(){
		var g = this,
			p = this.options;
		return p.columns[p.active];
	}
}

module.exports = tab;