Monatsarchiv für November 2014

 
 

jQuery.grab and Beyond – JavaScript Framework Thoughts Part 2

Templating

So, Backbone uses Underscore templates, which I never really used much because I’m such a huge Mustache fan. Anyway, like I said in the last post I’ve been using Ractive for templating a good deal for work, so I’ve been thinking about what a template might look like if it were in a framework that I wrote.

I sort of dabbled with this before… about three years ago with a jQuery plugin called jQuery.grab. The idea is, jQuery reads your grab template creates all the elements and wraps select elements in a jQuery object and automatically makes them properties of a given class (constructor object).

Here is the old github for jQuery.grab:
https://github.com/ZevanRosser/jquery.grab

The demos show how it works:
https://github.com/ZevanRosser/jquery.grab/tree/master/demos

So jQuery.grab isn’t really a template system but it enables views to be created and have relevant elements selected and wrapped in jQuery objects – which is cool and at the very least makes it so you don’t have a million selectors in your code.

So the extension of this is templates that can be bound to the type of object mentioned in the previous post. Additional, these templates should be smart and do as little dome manipulation as possible. Once an element gets created, it gets updated instead of recreated and for collections nodes should be appended if possible or smartly selected and removed.

My first stab at this was just to create the syntax for an ideal template. This will likely change as I continue to write the javascript but here is the first pass:

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
<script id="tmpl" type="text/html">
  <div class="app">
 
    <h2>.title</h2>
 
    <p>.some.nested.prop</p>
 
    <form>
      <input type="checkbox" checked=".checked">
    </form>
 
    <ul data-items>
      <li>.value</li>
    </ul>
 
    <select data-files>
      <option value=".id">.fileName</option>
    </select>
 
    <div data-names>
      <div class="name">.</div>
    </div>
 
    <div data-collection>
      <div class='thing'>
        <h2>.title</h2>
        <div data-things>
          .thing
        </div>
      </div>
    </div>
 
  </div> 
</script>

The idea here is that you would never include actual text content, but always have it in your JSON. Variables start with a . and collections are just defined by a data attribute where the second part of the attribute is the path to the corresponding collection, like this:

// our data and corresponding icons collection...
{
  settings : {
    icons : [
      {src : 'someImage.jpg', name : 'some image'},
      {src : 'someOtherImage.jpg', name : 'some other image'}
    ]
  }
}

… and our html:

1
2
3
<div class="items-collection" data-settings.icons>
  <img src=".src" /><span>.name</span><br/>
</div>

Something like that…

The cool thing with this is that the template will always be completely valid html so to build the template with javascript you can just use innerHTML on some div, then recursively process the nodes of the template to populate and data-bind them.

I’ve started work on the javascript for this but haven’t gotten it very far yet.

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