FIX #72
[euphorik.git] / js / fragment.js
1 // coding: utf-8
2 // Copyright 2008 Grégory Burri
3 //
4 // This file is part of Euphorik.
5 //
6 // Euphorik is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // Euphorik is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with Euphorik. If not, see <http://www.gnu.org/licenses/>.
18
19 /**
20 * Gestion du fragment d'url, permet de le modifier en direct.
21 */
22 Fragment = function() {
23 var thisFragment = this;
24 // remplacement des codes de type %22 (en hexa)
25 var replaceHtmlCode = function(str) {
26 return str.replace(/%(\d\d)/g, function(text, code) {
27 return String.fromCharCode(parseInt(code, 16));
28 })
29 };
30 this.fragments = {};
31 if (!window.location.hash) {
32 return;
33 }
34 try {
35 var fragmentsStr = replaceHtmlCode(window.location.hash.slice(1)).split(";");
36 fragmentsStr.each(function(i, tuple) {
37 tuple = tuple.split("=");
38 thisFragment.fragments[tuple[0]] = JSON.parse(tuple[1]);
39 });
40 } catch(error) {
41 alert(error)
42 ;; console.log(error);
43 }
44 };
45
46 Fragment.prototype.setVal = function(name, val) {
47 this.fragments[name] = val;
48 };
49
50 Fragment.prototype.getVal = function(name) {
51 return this.fragments[name];
52 };
53
54 Fragment.prototype.delVal = function(name) {
55 delete this.fragments[name];
56 };
57
58 Fragment.prototype.eraseAllVal = function() {
59 this.fragments = [];
60 };
61
62 Fragment.prototype.each = function(fun) {
63 objectEach(this.fragments, function(name, val) {
64 fun(name, val);
65 });
66 };
67
68 Fragment.prototype.write = function() {
69 var fragmentsStr = "";
70 var first = true;
71 objectEach(this.fragments, function(name, val) {
72 fragmentsStr += (first ? "" : ";") + name + "=" + JSON.stringify(val);
73 first = false;
74 });
75 window.location.hash = fragmentsStr;
76 };