-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo-standalone-self-contained.html
More file actions
1333 lines (1157 loc) · 45.3 KB
/
Copy pathdemo-standalone-self-contained.html
File metadata and controls
1333 lines (1157 loc) · 45.3 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>microMVC+ Demo 2026</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg : #f4f6f9;
--card : #ffffff;
--primary : #2563eb;
--accent : #10b981;
--danger : #ef4444;
--text : #1e293b;
--muted : #64748b;
--border : #e2e8f0;
--radius : 10px;
--shadow : 0 2px 12px rgba(0,0,0,0.08);
}
body {
font-family : system-ui, -apple-system, sans-serif;
background : var(--bg);
color : var(--text);
min-height : 100vh;
padding : 2rem 1rem;
}
header {
text-align : center;
margin-bottom : 2.5rem;
}
header h1 { font-size : 2rem; font-weight : 800; color : var(--primary); }
header p { color : var(--muted); margin-top : 0.4rem; font-size : 1rem; }
.badge-row {
display : flex;
flex-wrap : wrap;
justify-content : center;
gap : 0.5rem;
margin-top : 0.8rem;
}
.badge {
background : var(--primary);
color : #fff;
font-size : 0.72rem;
font-weight : 600;
padding : 3px 10px;
border-radius : 20px;
letter-spacing: 0.02em;
}
.badge.green { background : var(--accent); }
.badge.gray { background : var(--muted); }
.demos {
display : grid;
grid-template-columns : repeat(auto-fit, minmax(320px, 1fr));
gap : 1.5rem;
max-width : 1100px;
margin : 0 auto;
}
.card {
background : var(--card);
border-radius : var(--radius);
box-shadow : var(--shadow);
padding : 1.5rem;
border : 1px solid var(--border);
}
.card h2 {
font-size : 1.05rem;
font-weight : 700;
margin-bottom : 0.3rem;
color : var(--primary);
}
.card p.desc {
font-size : 0.85rem;
color : var(--muted);
margin-bottom : 1rem;
}
label {
display : block;
font-size : 0.82rem;
font-weight : 600;
margin-bottom : 0.3rem;
color : var(--muted);
}
input, select {
width : 100%;
padding : 0.5rem 0.75rem;
border : 1px solid var(--border);
border-radius : 6px;
font-size : 0.9rem;
margin-bottom : 0.8rem;
color : var(--text);
background : #fff;
}
button {
padding : 0.5rem 1.2rem;
border-radius : 6px;
border : none;
cursor : pointer;
font-weight : 600;
font-size : 0.88rem;
transition : opacity 0.15s;
}
button:hover { opacity : 0.85; }
button:disabled { opacity : 0.4; cursor : not-allowed; }
.btn-primary { background : var(--primary); color : #fff; }
.btn-accent { background : var(--accent); color : #fff; }
.btn-danger { background : var(--danger); color : #fff; }
.btn-outline { background : transparent; border : 1px solid var(--border); color : var(--text); }
.btn-row {
display : flex;
gap : 0.5rem;
flex-wrap: wrap;
}
.result-box {
margin-top : 1rem;
padding : 0.9rem 1rem;
background : var(--bg);
border-radius : 8px;
border : 1px solid var(--border);
font-size : 0.88rem;
min-height : 50px;
}
.balance {
font-size : 2rem;
font-weight : 800;
color : var(--accent);
display : block;
margin : 0.5rem 0;
}
.balance.negative { color : var(--danger); }
.notification-bell {
position : relative;
display : inline-block;
font-size : 1.8rem;
cursor : pointer;
user-select : none;
}
.notif-badge {
position : absolute;
top : -4px;
right : -8px;
background : var(--danger);
color : #fff;
font-size : 0.65rem;
font-weight : 800;
border-radius : 20px;
padding : 1px 5px;
min-width : 18px;
text-align : center;
}
.notif-list {
margin-top : 0.8rem;
font-size : 0.83rem;
}
.notif-item {
padding : 0.4rem 0.6rem;
border-radius : 6px;
margin-bottom : 0.3rem;
background : #eff6ff;
color : var(--primary);
border-left : 3px solid var(--primary);
}
.task-list {
list-style : none;
margin : 0.8rem 0;
}
.task-item {
display : flex;
align-items : center;
gap : 0.5rem;
padding : 0.4rem 0;
border-bottom : 1px solid var(--border);
font-size : 0.88rem;
}
.task-item.done span { text-decoration : line-through; color : var(--muted); }
.task-item button {
margin-left : auto;
padding : 2px 8px;
font-size : 0.75rem;
border-radius : 4px;
}
.profile-zone {
display : flex;
align-items : center;
gap : 1rem;
margin : 0.8rem 0;
}
.avatar {
width : 64px;
height : 64px;
border-radius : 50%;
background : var(--primary);
display : flex;
align-items : center;
justify-content : center;
font-size : 1.8rem;
color : #fff;
font-weight : 800;
flex-shrink : 0;
overflow : hidden;
}
.avatar img { width : 100%; height : 100%; object-fit : cover; }
.profile-info { font-size : 0.9rem; }
.profile-info strong { display : block; font-size : 1rem; }
.profile-info span { color : var(--muted); font-size : 0.82rem; }
.log-box {
background : #0f172a;
color : #94a3b8;
border-radius : 8px;
padding : 0.8rem 1rem;
font-family : monospace;
font-size : 0.78rem;
max-height : 160px;
overflow-y : auto;
margin-top : 1rem;
}
.log-box p { margin-bottom : 0.2rem; }
.log-box .ts { color : #475569; margin-right : 0.5rem; }
.log-box .ctx { color : #38bdf8; }
.log-box .val { color : #a3e635; }
.status-pill {
display : inline-block;
padding : 2px 10px;
border-radius : 20px;
font-size : 0.75rem;
font-weight : 700;
}
.status-pill.ok { background : #d1fae5; color : #065f46; }
.status-pill.err { background : #fee2e2; color : #991b1b; }
.status-pill.wait { background : #fef3c7; color : #92400e; }
.progress-bar {
height : 8px;
background : var(--border);
border-radius : 4px;
margin : 0.6rem 0;
overflow : hidden;
}
.progress-fill {
height : 100%;
background : var(--accent);
transition : width 0.4s ease;
border-radius : 4px;
}
footer {
text-align : center;
color : var(--muted);
font-size : 0.8rem;
margin-top : 3rem;
}
</style>
</head>
<body>
<header>
<h1>microMVC+</h1>
<p>Zero-dependency JavaScript MVC micro-framework. Interactive demos for 2026.</p>
<div class="badge-row">
<span class="badge">v1.0.0</span>
<span class="badge green">Zero dependencies</span>
<span class="badge gray">MIT License</span>
<span class="badge">ES5+ compatible</span>
</div>
</header>
<div class="demos">
<!-- DEMO 1 : Bank transfer -->
<div class="card">
<h2>Demo 1 : Instant bank transfer</h2>
<p class="desc">
The model holds your balance. The view listens. When the controller validates
the transfer, the view updates instantly without any page reload.
</p>
<label>Your current balance</label>
<span class="balance" id="balance-display">2 500.00 EUR</span>
<div class="progress-bar">
<div class="progress-fill" id="balance-bar" style="width: 100%"></div>
</div>
<label>Transfer amount (EUR)</label>
<input type="number" id="transfer-amount" value="200" min="1" />
<label>Recipient</label>
<input type="text" id="transfer-recipient" value="Alice Martin" />
<div class="btn-row">
<button class="btn-primary" id="btn-transfer">Send transfer</button>
<button class="btn-outline" id="btn-reset-bank">Reset</button>
</div>
<div class="result-box" id="bank-log">Waiting for a transfer...</div>
</div>
<!-- DEMO 2 : Notification center -->
<div class="card">
<h2>Demo 2 : Real-time notifications</h2>
<p class="desc">
One model, three views updated at the same time with a single publish call.
This is the exact Facebook-style scenario : bell, tab title, and list all in sync.
</p>
<div class="profile-zone">
<div>
<div class="notification-bell">
<span id="notif-bell-icon">bell</span>
<span class="notif-badge" id="notif-count-bell">0</span>
</div>
</div>
<div style="flex: 1; font-size: 0.85rem; color: var(--muted);">
Tab title counter : <strong id="notif-count-tab">0 notifications</strong><br />
Bell counter : <strong id="notif-count-header">0</strong>
</div>
</div>
<div class="btn-row">
<button class="btn-primary" id="btn-add-notif">Receive a notification</button>
<button class="btn-outline" id="btn-clear-notif">Mark all read</button>
</div>
<div class="notif-list" id="notif-list"></div>
</div>
<!-- DEMO 3 : Task manager with state -->
<div class="card">
<h2>Demo 3 : Task manager with state</h2>
<p class="desc">
Demonstrates the new setState/getState API on models. The view reacts to any
state change automatically via the "state.changed" event.
</p>
<label>New task</label>
<input type="text" id="task-input" placeholder="e.g. Review the pull request" />
<div class="btn-row">
<button class="btn-accent" id="btn-add-task">Add task</button>
<button class="btn-outline" id="btn-clear-tasks">Clear all</button>
</div>
<ul class="task-list" id="task-list"></ul>
<div class="result-box" id="task-stats">No tasks yet.</div>
</div>
<!-- DEMO 4 : Profile editor -->
<div class="card">
<h2>Demo 4 : Live profile editor</h2>
<p class="desc">
Type in the fields and watch the profile card update instantly.
Demonstrates once() : the welcome message fires only the first time you save.
</p>
<div class="profile-zone">
<div class="avatar" id="profile-avatar">F</div>
<div class="profile-info">
<strong id="profile-name">Fabien Conéjéro</strong>
<span id="profile-role">Frontend Developer</span>
</div>
</div>
<label>Full name</label>
<input type="text" id="input-name" value="Fabien Conéjéro" />
<label>Role</label>
<input type="text" id="input-role" value="Frontend Developer" />
<div class="btn-row">
<button class="btn-primary" id="btn-save-profile">Save profile</button>
</div>
<div class="result-box" id="profile-status">
<span class="status-pill ok">Saved</span> Profile ready.
</div>
</div>
<!-- DEMO 5 : Event log / debugger -->
<div class="card">
<h2>Demo 5 : Event log (new in v1.0.0)</h2>
<p class="desc">
Every publish call is logged automatically. Use this during development
to trace the exact sequence of events across your components.
</p>
<div class="btn-row">
<button class="btn-primary" id="btn-show-log">Show log</button>
<button class="btn-outline" id="btn-clear-log">Clear log</button>
</div>
<div class="log-box" id="event-log">
<p>Interact with the demos above, then click "Show log".</p>
</div>
</div>
<!-- DEMO 6 : publishAsync -->
<div class="card">
<h2>Demo 6 : publishAsync (Promise-based)</h2>
<p class="desc">
Fire an event asynchronously and chain logic after all subscribers
have been notified. Useful for loading states and sequential flows.
</p>
<div class="btn-row">
<button class="btn-primary" id="btn-async-start">Run async flow</button>
</div>
<div class="result-box" id="async-log">Click the button to start.</div>
</div>
</div>
<footer>
<p>microMVC+ v1.0.0 - Author : Fabien Conéjéro (2026) - MIT License</p>
</footer>
<script>
/**
* microMVC+
* A modern, zero-dependency JavaScript MVC micro-framework.
*
* Author : Fabien Conéjéro
* Version : 1.0.0
* Date : February 2026
* License : MIT
* Repository : https://github.com/madjeek-web
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.microMVC = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
'use strict';
/**
* ELEMENT
*
* The base object that every model, view, and controller element inherits from.
* It knows its own id and which component it belongs to.
* It can publish events upward to its component.
*
* --- For a 14-year-old ---
* Think of an Element like a player in a team. Each player has a name (id),
* knows which team they play for (component), and can shout things to the team.
*
* --- For a junior dev ---
* Element is the base prototype for all registered MVC pieces.
* It holds a reference to its parent Component and exposes publish shortcuts.
*
* --- For teachers and trainers ---
* Element acts as the base mediator object. It is instantiated indirectly via
* Component.add(). The _constructor hook replaces the native constructor to
* allow deferred initialization after prototype assembly.
*/
var Element = function () {};
Element.prototype = {
/**
* _constructor
* Called automatically after the element is built and registered.
* Override this in your element definition to run setup code.
*/
_constructor : function () {},
/**
* publish
* Fires a namespaced event scoped to this element within its component.
* The full context becomes : elementId.yourContext
*
* @param {string} context - Event name (e.g. "onLogin")
* @param {object} event - Data payload to send to subscribers
*/
publish : function (context, event) {
this._component.publish(this._id + '.' + context, event);
},
/**
* publishAsync
* Same as publish but deferred to the next event loop tick.
* Returns a Promise so callers can chain or await.
*
* --- For a junior dev ---
* Useful when you need to ensure the DOM has updated before notifying,
* or when you want non-blocking fire-and-forget notifications.
*
* @param {string} context - Event name
* @param {object} event - Data payload
* @returns {Promise}
*/
publishAsync : function (context, event) {
return this._component.publishAsync(this._id + '.' + context, event);
},
/**
* destroy
* Removes this element from its component.
*/
destroy : function () {
this._component.remove(this._id);
}
};
/**
* COMPONENT
*
* A container that holds elements (models, views, or controllers).
* It manages the publish/subscribe messaging bus that allows all pieces to talk.
*
* --- For a 14-year-old ---
* Think of a Component like a WhatsApp group chat. Anyone in the group
* can send a message (publish) and anyone who subscribed will receive it.
* You can also leave the group at any time (unsubscribe).
*
* --- For a junior dev ---
* Component is a mediator. It holds a namespaced subscriber tree and fires
* callbacks when matching contexts are published. It also serves as the
* registry for all named elements.
*
* --- For teachers and trainers ---
* The subscriber namespace is a plain recursive object tree, traversed by a
* regex walker. Each node stores a _subscribers array. The publish method
* walks the tree and invokes callbacks at each matching depth level.
* This design allows hierarchical event bubbling with dot-notation scoping.
*/
var Component = function (app) {
this.__app__ = app;
this.subscribers = {};
this._log = [];
};
Component.prototype = {
/**
* add
* Registers a new element inside this component.
*
* @param {string} id - Unique name for the element (e.g. "userModel")
* @param {object} obj - Object with the element's methods and properties
* @param {function} ext - Optional base class to extend (default : Element)
* @returns {object} The created element instance
*/
add : function (id, obj, ext) {
if (this.has(id)) {
console.warn('microMVC : element "' + id + '" already exists. Returning existing instance.');
return this[id];
}
ext = ext || Element;
var element = function () {};
element.prototype = new ext();
element.prototype._id = id;
element.prototype._component = this;
element.prototype.controllers = this.__app__.controllers;
element.prototype.models = this.__app__.models;
element.prototype.views = this.__app__.views;
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
element.prototype[attr] = obj[attr];
}
}
this[id] = new element();
this[id]._constructor();
return this[id];
},
/**
* has
* Checks whether an element with the given id exists in this component.
*
* @param {string} id
* @returns {boolean}
*/
has : function (id) {
return this[id] !== undefined && this[id] !== null;
},
/**
* remove
* Unregisters and deletes an element from this component.
*
* @param {string} id
* @returns {Component} this (chainable)
*/
remove : function (id) {
if (!this.has(id)) {
console.warn('microMVC : element "' + id + '" not found. Nothing to remove.');
return this;
}
delete this[id];
return this;
},
/**
* call
* Calls a method on a named element using dot-notation path.
*
* @param {string} path - "elementId.methodName" (e.g. "userCtrl.login")
* @param {*} argument - Single argument passed to the method
* @returns {*} The return value of the called method, or null
*/
call : function (path, argument) {
var match;
if ((match = /^(.*?)\.(.*)$/.exec(path)) !== null) {
var id = match[1];
var method = match[2];
if (this.has(id) && typeof this[id][method] === 'function') {
return this[id][method](argument);
}
console.warn('microMVC : call failed for "' + path + '". Check element id and method name.');
}
return null;
},
/**
* publish
* Fires an event on a dot-namespaced context.
* All subscribers listening to any matching level of the namespace are called.
*
* @param {string} context - Namespaced event (e.g. "userModel.onLogin")
* @param {object} event - Data sent to subscribers
* @returns {Component} this (chainable)
*/
publish : function (context, event) {
event = event || {};
var re = new RegExp('[.]*([^.]+)[.]*', 'g');
var m;
var ns = this.subscribers;
this._log.push({ time : Date.now(), context : context, event : event });
while ((m = re.exec(context)) !== null && ns[m[1]]) {
if (m.index === re.lastIndex) { re.lastIndex++; }
ns = ns[m[1]];
if (ns._subscribers) {
var toRemove = [];
for (var i = 0; i < ns._subscribers.length; i++) {
ns._subscribers[i].callback.call(ns._subscribers[i].scope, event);
if (ns._subscribers[i].once) {
toRemove.push(i);
}
}
for (var j = toRemove.length - 1; j >= 0; j--) {
ns._subscribers.splice(toRemove[j], 1);
}
}
}
return this;
},
/**
* publishAsync
* Deferred version of publish. Returns a Promise.
* Resolves once the event has been dispatched to all subscribers.
*
* @param {string} context
* @param {object} event
* @returns {Promise<{context, event}>}
*/
publishAsync : function (context, event) {
var self = this;
return new Promise(function (resolve) {
setTimeout(function () {
self.publish(context, event);
resolve({ context : context, event : event });
}, 0);
});
},
/**
* subscribe
* Listens to a namespaced event context. Callback fires every time it is published.
*
* @param {string} context - Namespaced event to listen to
* @param {object} scope - The 'this' value inside the callback
* @param {function} callback - Function called with the event payload
* @returns {string} A unique subscription token (used to unsubscribe later)
*/
subscribe : function (context, scope, callback) {
return this._addSubscriber(context, scope, callback, false);
},
/**
* once
* Like subscribe but fires only once, then removes itself automatically.
*
* --- For a 14-year-old ---
* It is like a one-time notification. You get the alert once, then it disappears.
*
* @param {string} context
* @param {object} scope
* @param {function} callback
* @returns {string} Subscription token
*/
once : function (context, scope, callback) {
return this._addSubscriber(context, scope, callback, true);
},
/**
* unsubscribe
* Removes a subscription using its token returned by subscribe() or once().
*
* @param {string} token - The token returned by subscribe() or once()
* @returns {Component} this (chainable)
*/
unsubscribe : function (token) {
this._removeByToken(this.subscribers, token);
return this;
},
/**
* getLog
* Returns a copy of the event log for debugging purposes.
*
* @returns {Array} Array of logged publish calls
*/
getLog : function () {
return this._log.slice();
},
/**
* clearLog
* Empties the event log.
*
* @returns {Component} this (chainable)
*/
clearLog : function () {
this._log = [];
return this;
},
/**
* destroy
* Wipes all subscribers and the event log from this component.
*
* @returns {Component} this (chainable)
*/
destroy : function () {
this.subscribers = {};
this._log = [];
return this;
},
/**
* _addSubscriber (internal)
* Registers a callback in the subscriber namespace tree.
*/
_addSubscriber : function (context, scope, callback, isOnce) {
var re = new RegExp('[.]*([^.]+)[.]*', 'g');
var m;
var ns = this.subscribers;
while ((m = re.exec(context)) !== null) {
if (m.index === re.lastIndex) { re.lastIndex++; }
ns[m[1]] = ns[m[1]] || {};
ns = ns[m[1]];
}
ns._subscribers = ns._subscribers || [];
var token = 'sub_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);
ns._subscribers.push({
token : token,
context : context,
scope : scope,
callback : callback,
once : isOnce
});
return token;
},
/**
* _removeByToken (internal)
* Recursively searches the subscriber tree to remove a subscription by token.
*/
_removeByToken : function (ns, token) {
if (ns._subscribers) {
for (var i = ns._subscribers.length - 1; i >= 0; i--) {
if (ns._subscribers[i].token === token) {
ns._subscribers.splice(i, 1);
return true;
}
}
}
for (var key in ns) {
if (key !== '_subscribers' && ns.hasOwnProperty(key)) {
if (this._removeByToken(ns[key], token)) { return true; }
}
}
return false;
}
};
/**
* APPLICATION
*
* The root object. Holds the three components : controllers, views, models.
* The models component has extra state management capabilities built in.
*
* --- For a 14-year-old ---
* The Application is like the school itself. Inside there are three departments :
* the teachers (controllers), the classrooms (views), and the library (models).
* Everyone can talk to everyone through the school's messaging system.
*
* --- For a junior dev ---
* Application wires the three Component instances together and patches the
* models component with a simple key-value state store that publishes events
* on every mutation, making reactive data binding trivial to implement.
*
* --- For teachers and trainers ---
* The state store on models is intentionally kept outside of the Component
* prototype to avoid coupling. It is added directly on the instance in the
* Application constructor, following a flat composition preference
* over deep inheritance chains.
*/
var Application = function () {
this.controllers = new Component(this);
this.views = new Component(this);
this.models = new Component(this);
this._initModelState();
};
Application.prototype.VERSION = '1.0.0';
/**
* _initModelState (internal)
* Patches the models component with reactive state management.
* Uses closure to keep the state object private.
*/
Application.prototype._initModelState = function () {
var state = {};
var models = this.models;
/**
* models.getState
* Returns the current value for a key, or a full shallow copy of all state.
*
* @param {string} [key] - Optional key. If omitted, returns all state.
* @returns {*}
*/
models.getState = function (key) {
if (key === undefined) {
var copy = {};
for (var k in state) {
if (state.hasOwnProperty(k)) { copy[k] = state[k]; }
}
return copy;
}
return state.hasOwnProperty(key) ? state[key] : undefined;
};
/**
* models.setState
* Updates a state key and publishes "state.changed" with old and new values.
* Any view subscribed to "state.changed" will react automatically.
*
* @param {string} key
* @param {*} value
* @returns {Component} models (chainable)
*/
models.setState = function (key, value) {
var previous = state[key];
state[key] = value;
models.publish('state.changed', {
key : key,
value : value,
previous : previous
});
return models;
};
/**
* models.resetState
* Clears all state and publishes "state.reset".
*
* @returns {Component} models (chainable)
*/
models.resetState = function () {
state = {};
models.publish('state.reset', {});
return models;
};
};
/**
* destroy
* Tears down the entire application : clears all components and state.
* Useful for single-page app route transitions.
*
* @returns {Application} this (chainable)
*/
Application.prototype.destroy = function () {
this.controllers.destroy();
this.views.destroy();
this.models.destroy();
this.models.resetState();
return this;
};
return {
Application : Application,
VERSION : '1.0.0'
};
}));
</script>
<script>
(function () {
'use strict';
// ----------------------------------------------------------------
// Bootstrap the application
// ----------------------------------------------------------------
var app = new microMVC.Application();
// ----------------------------------------------------------------
// DEMO 1 : Bank transfer
// ----------------------------------------------------------------
var INITIAL_BALANCE = 2500;
app.models.add('bankModel', {
_balance : INITIAL_BALANCE,
getBalance : function () {
return this._balance;
},
transfer : function (amount, recipient) {
if (typeof amount !== 'number' || amount <= 0) {
this.publish('transferError', { message : 'Invalid amount.' });
return;
}
if (amount > this._balance) {
this.publish('transferError', { message : 'Insufficient funds.' });
return;
}
this._balance = Math.round((this._balance - amount) * 100) / 100;
this.publish('balanceChanged', {
balance : this._balance,
amount : amount,
recipient : recipient
});
},
reset : function () {
this._balance = INITIAL_BALANCE;
this.publish('balanceChanged', { balance : this._balance, amount : 0, recipient : null });
}
});
app.views.add('bankView', {
_constructor : function () {
this.models.subscribe('bankModel.balanceChanged', this, this.onBalanceChanged);
this.models.subscribe('bankModel.transferError', this, this.onError);
},
onBalanceChanged : function (e) {
var el = document.getElementById('balance-display');
var bar = document.getElementById('balance-bar');
var log = document.getElementById('bank-log');
el.textContent = formatEuro(e.balance);
el.className = 'balance' + (e.balance < 0 ? ' negative' : '');