Archiv der Kategorie ‘html‘

 
 

Zapp and Beyond – JavaScript Framework Thoughts Part 1

Three years ago I was using Backbone and other similar frameworks for the first time… as an experiment I created Zapp, which was a super minimalistic variation on the idea of easy Object instantiation with inheritance, routers/deep linking and custom events. Here is the old repository:

https://github.com/ZevanRosser/Zapp

The source for Zapp is pretty short:

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
var Zapp = Zapp ||
function(a, b, c) {
  b = b || {};
  c = c || {};
  if (typeof a != "function") {
    b = a;
    a = Zapp._ctor;
  }
  if (typeof a == "function" && !b.prototype) {
    b.constructor = a;
    a.prototype = b;
    return a;
  } else if (typeof a == "function" && typeof b == "function") {
 
    b.prototype = new a();
    b.prototype.constructor = b;
 
    for (var i in c) {
      b.prototype[i] = c[i];
    }
    b.prototype.proto = a.prototype;
    b.prototype.sup = function() {
      a.apply(this, arguments);
    }
    return b;
  }
  return {};
};
 
Zapp.Object = Zapp;
 
Zapp._ctor = function() {};
 
Zapp.Events = function() {};
 
Zapp.Events.prototype = {
  constructor : Zapp.Events,
  _makeListeners: function() {
    this._listeners = this._listeners || [];
  },
  trigger: function(type, data) {
    this._makeListeners();
    var leng = this._listeners.length;
    for (var i = 0; i < leng; i++) {
      var listener = this._listeners[i];
      if (listener == undefined) continue;
      if (listener.type == type) {
        listener.callback.call(listener.ctx || this, data);
      }
    }
    return this;
  },
  on: function(type, callback, ctx) {
    this._makeListeners();
    this._listeners.push({
      type: type,
      callback: callback,
      ctx: ctx
    });
    return this;
  },
  off: function(type, callback) {
    this._makeListeners();
    for (var i = 0; i < this._listeners.length; i++) {
      var listener = this._listeners[i];
      if (listener == undefined) continue;
 
      if (listener.type == type && (listener.callback == callback || callback == undefined)) {
        this._listeners.splice(i, 1);
      }
    }
    return this;
  },
  allOff: function() {
    this._listeners = [];
    return this;
  }
};
 
// this code needs cleanup
//#path //exact match
//#path/name,name,name // values
//^path // regexp?
Zapp.Router = Zapp(Zapp.Events, function() {
  var self = this;
  if (Zapp.Router._instance) return Zapp.Router._instance;
  Zapp.Router._instance = self;
 
  var prevHash = "";
  var grabHash = /#(.*?)$/;
  var grabTrailingSlash = /\/$/;
 
  function getHash(){
    var hash = window.location.href.match(grabHash);
    return hash ? hash[1] : "";
  }
 
  if (getHash() == ""){
    setTimeout(function(){
      self.trigger("/");
      //self.trigger("change", {hash:"/"});
    }, 2);
 
  }else{
    setTimeout(checkHash, 2); 
  }
 
  function checkHash() {
    var hash = getHash();
    if (prevHash != hash) {
      if (hash == ""){
        self.trigger("/");
        return;
      }
      self.trigger("change", {hash:hash});
      for (var i = 0; i < self._listeners.length; i++) {
        var type = self._listeners[i].type;
        if (type == hash) {
 
          self.trigger(type);
          continue;
        }
        if (hash.match(new RegExp(type))) {
          self.trigger(type);
          continue;
        }
        var names = type.split(",");
        var startsWith = new RegExp("^" + names[0]);
        var starts = hash.match(startsWith);
        if (starts) {
 
          var values = hash.replace(startsWith, "");
 
          values = values.replace(grabTrailingSlash, "");
 
          values = values.substr(1).split("/");
 
          if (names.length - 1 == values.length) {
            var data = {};
 
            for (var j = 1; j < names.length; j++) {
 
              data[names[j]] = values[j - 1];
 
            }
            self.trigger(type, data);
 
          } else {
            continue;
          }
        }
 
      }
      prevHash = hash;
    }
  }
  setInterval(checkHash, 100);
 
}, {
  is: function() {
    this.on.apply(this, arguments);
    return this;
  },
  clear: function() {
    this.off.apply(this, arguments);
    return this;
  },
  clearAll: function() {
    this.allOff.apply(this, arguments);
    return this;
  }
});

The demos for Zapp give you an idea of how it works:

https://github.com/ZevanRosser/Zapp/tree/master/demos

Anyway, I’ve been heavily using Backbone along with Ractive (for templating) these days. And, well, it got me thinking of how I would like this stuff to work if I were to write my own framework. I know I may not use it if I write it, but just like Zapp, it could be interesting to think about again.

The first thing I was thinking about was how frameworks like Ractive and Backbone use get and set methods:

1
2
3
this.set('someValue', 100);
// or
this.get('someValue);

This enables events to occur when a value on a model or view changes so that a template can update or some other part of your program can update. I thought it would be cool to do something different…

This is really just a first though, but what if properties on an object literal were accompanied by a method that set them – of the same name prefixed by something like a $ or even set and then camel case the property:

1
2
3
4
5
6
// get a variable like normal:
var myName = obj.person.name;
//set it with the new method:
obj.person.$name('Zevan'); 
// now
obj.person.name = 'Zevan';

With some tweaking I was able to get a prototype of this functionality to work:

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
(function() {
 
  if (!Array.isArray) {
    Array.isArray = function(arg) {
      return Object.prototype.toString.call(arg) === '[object Array]';
    };
  }
 
  window.Watch = function(data) {
    this.data = this.process(data);
  };
 
  Watch.prototype = {
    constructor : Watch,
    process : function(obj, keyPath) {
      var path, temp, key;
      keyPath = keyPath ? keyPath + '.' : '';
 
      if(obj === null || typeof(obj) !== 'object') return obj;
 
      temp = obj.constructor(); 
 
      for(key in obj) {
        if(obj.hasOwnProperty(key)) {
          path = keyPath + key;
          temp[key] = this.process(obj[key], path);
          (function(key, path) {
            temp['$' + key] = function(val, silent) {
              temp[key] = val;
              // dispatch some event
              console.log('set', '"' + path + '"', '=', val);
            }; 
            if (Array.isArray(temp[key])){
              temp['$' + key].refresh = function() {
                // dispatch some event
                console.log('refresh collection', path);
              };
            }
          })(key, path);
        }
      }
 
      return temp;
    }
  };
})();

So the way this works is like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var obj = {
  x : 100, 
  y : 100,
  vect : {a : 1, b: 2, c : 3} 
};
 
var w = new Watch(obj);
 
console.log('"x" start value = ', w.data.x); 
 
w.data.$x(2);
 
console.log('"x" is now', w.data.x); 
 
console.log('original "x" is still', obj.x);
 
console.log('------Something Different------');
 
console.log('"vect.a" start value = ', w.data.x); 
 
w.data.vect.$a('I am a!');
 
console.log(w.data.vect.a);

Which will output:

1
2
3
4
5
6
7
8
"x" start value =  100 watch5.html:19
set "x" = 2 watch.js:31
"x" is now 2 watch5.html:23
original "x" is still 100 watch5.html:25
------Something Different------ watch5.html:27
"vect.a" start value =  2 watch5.html:29
set "vect.a" = I am a! watch.js:31
I am a!

So, that’s pretty interesting, and if you JSON.stringify() the object, all the functions get removed which is nice if you need to pass the new JSON off to the server or something.

HTML5 Canvas Spinners

This is an old canvas experiment I did awhile back. A few weeks ago I ported it over to CoffeeScript and posted it on codepen:

See the Pen Spinners by Zevan Rosser (@ZevanRosser) on CodePen.

There’s nothing much going on in the HTML or CSS, although I did use Sass for no real reason… The CoffeeScript is where everything happens:

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
window.onload = () ->
  SIZE = 400
  quarterSize = SIZE / 4
  threQuarters = SIZE - quarterSize;
  TWO_PI = Math.PI * 2
 
  createCanvas = () ->
    canvas = document.createElement "canvas"
    canvas.width = SIZE
    canvas.height = SIZE
    canvas
 
  canvas = createCanvas()
  document.body.appendChild(canvas)
  c = canvas.getContext("2d")
  trails = createCanvas() 
  ct = trails.getContext("2d")
 
  clear = ->
    c.fillStyle = "black"
    c.fillRect 0, 0, SIZE, SIZE
    ct.fillStyle = "black"
    ct.fillRect 0, 0, SIZE, SIZE
    return
 
  clear()
  document.getElementById("erase").onclick = clear
 
  class DrawingThing
    constructor : (x, y) ->
      @x = x
      @y = y
      @radii = [30 , 60, 90]
      @num = @radii.length
      @thetas = [Math.random() * TWO_PI
                 Math.random() * TWO_PI
                 Math.random() * TWO_PI]
      @thetasInc = [Math.random() * 0.2 - 0.1
                    Math.random() * 0.2 - 0.1 
                    Math.random() * 0.2 - 0.1]
 
    draw : ->
      ct.strokeStyle = "rgba(255,255,255,0.1)"
      for i in [0...@num]
        x = @x + @radii[i] * Math.cos(@thetas[i])
        y = @y + @radii[i] * Math.sin(@thetas[i])
 
        if i == 0
          ct.beginPath();
          ct.moveTo(x, y);
        else
          ct.lineTo(x, y);
 
        c.strokeStyle = "rgba(255,255,255,0.5)"
        c.fillStyle = "white"
        c.beginPath()
        c.arc(@x, @y, @radii[i], 0, TWO_PI, false)
        c.stroke();
 
        c.beginPath();
        c.arc(x, y, 2, 0, TWO_PI, false);
        c.fill();
        @thetas[i] += @thetasInc[i];
 
      ct.closePath();
      ct.stroke();
 
      return
 
  drawingThings = [new DrawingThing(quarterSize, quarterSize)
                   new DrawingThing(threQuarters, quarterSize)
                   new DrawingThing(threQuarters, threQuarters)
                   new DrawingThing(quarterSize , threQuarters)];
 
  setInterval(->
    c.drawImage(trails, 0, 0)
 
    for drawThing in drawingThings
      drawThing.draw()
 
   , 30);
 
  return

Random Spotify Covers

A few weeks ago I created a demo using CoffeeScript, Twitter Bootstrap, jQuery and Mustache. It grabs data from the Spotify API to display a bunch of random album covers:

See the Pen Random Spotify Covers by Zevan Rosser (@ZevanRosser) on CodePen.

The html is pretty straight forward and includes a small mustache template

1
2
3
4
5
6
7
8
9
10
11
<div class="container-fluid">
  <h1 class="title">Random Spotify Covers <span>click anywhere to regenerate</span></h1>
  <div class="rand-covers row">
  </div>
</div>
 
<script id="cover" type="text/html">
  <div class="cover col-lg-2 col-sm-3 col-xs-3">
    <img src="{{src}}">
  </div>
</script>

The CSS is also pretty straight forward. Bootstrap is included for the responsive images and prefix-free is used for the text-shadow.

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
/* bootstrap is included */
body{
  background : black;
  cursor : pointer;
}
.title{
  color : white;
  position : fixed;
  top: 30px;
  left : 0px;
  padding-left : 30px;
  padding-top : 10px;
  padding-bottom : 10px;
  z-index : 1000;
  width : 100%;
  background : rgba(0,0,0,0.7);
  text-shadow : 0px 0px 10px black,
                0px 0px 10px black;
 
}
.title span{
  font-size : 18px;
}
.cover{
  padding-left : 0px;
  padding-right : 0px; 
}
.cover img{
  width : 100%; 
}

The real trick happens in the CoffeeScript on line 16 where the query string for the Spotify API is randomly generated:

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
$ ->
  class RandomCovers
 
    constructor : ->
      @alph = "abcdefghijklmnopqrstuvwxyz1234567890".split ""
      @randCovers = $ ".rand-covers"
      @tmpl = Mustache.compile $("#cover").html()
 
      @randomAlbums()
 
     randomAlbums : =>
       a = @alph[parseInt(@alph.length * Math.random())]
       b = @alph[parseInt(@alph.length * Math.random())]
 
       @randCovers.html ""
       $.get "https://api.spotify.com/v1/search?q=#{a}*%20%20#{b}*&type=album", @renderAlbums
       return
 
     renderAlbums : (d) =>
       items = d.albums.items
 
       for item in items
          img = item.images[1]
          if img.height ==  300 and img.width == 300 
            url = img.url
            url = url.replace "http://i.scdn.co/", "http://o.scdn.co/"
 
            $(@tmpl src : url).appendTo @randCovers
       return
 
  randomCovers = new RandomCovers();
  $(document).click randomCovers.randomAlbums