-
Notifications
You must be signed in to change notification settings - Fork 2
/
menu.js
85 lines (73 loc) · 2.4 KB
/
menu.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var _ = require('./../../node_modules/underscore');
var util = require('util');
function Menu(config) {
this._init(config);
}
var menu_id = 0;
Menu.prototype = {
_init:function (config) {
_.extend(this, config);
this._menu_id = ++menu_id;
if (this.children && _.isArray(this.children)){
for (var i = 0; i < this.children.length; ++i){
this.children[i] = new Menu(this.children[i]);
}
}
},
title:'',
link:'',
visible:function (env) {
return true;
},
active:function (env) {
return false;
},
children:[],
template:'<div class="menu"><a href="%s" class="menu_item%s">%s</a>%s</div>',
children_template:'<div class="menu_children">%s</div>',
render:function (env) {
// console.log('rendering #%s:%s', this._menu_id, this.title);
if (!this.visible(env)) {
return '';
}
var ctx_class = this.active(env) ? ' active' : '';
// console.log(' ---------- rendering %s children of #%s: %s', this.children.length, this._menu_id, this.title);
var children_rendered = this._render_children(env);
return util.format(this.template, this.link, ctx_class, this.title, children_rendered);
},
add_child:function (child) {
var menu = new Menu(child);
// console.log('adding child #%s:%s to %s:%s', menu._menu_id, menu.title, this._menu_id, this.title);
this.children.push(menu);
},
_render_children:function (env) {
if (!this.children.length) {
return '';
}
var menu = this;
var child_items = [];
this.children.forEach(function (child, i) {
try {
if (child.visible(env)) {
// console.log('rendering child %s of #%s:%s - #%s:%s', i, menu._menu_id, menu.title, child._menu_id, child.title);
child_items.push(child.render(env));
}
} catch (e) {
console.log('err: %s', util.inspect(e));
}
});
if (child_items.length > 0) {
var ci = child_items.join("\n");
// console.log('ci: %s', ci);
return util.format(this.children_template, ci);
} else {
return '';
}
}
}
module.exports = {
Menu:Menu,
create:function (config) {
return new Menu(config);
}
}