Archiv der Kategorie ‘javascript‘

 
 

JavaScript Framework Thoughts Part 3

Today I had a chance to write the first proof of concept for the templating idea mentioned in part 2 of this post series. Really didn’t expect to get it working so quick but here it is:

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
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="obj.js"></script>
    <script>
      $(function(){
 
        var data = {
          title : 'cool',
          titleStyle : 'color : red',
          some : { 
            nested : {
              prop : 'you got it'
            }
          },
          checked : false,
          items : [
            {value : 1},
            {value : 2},
            {value : 3}
          ], 
          files : [
            {id : 123, fileName : 'one'},
            {id : 321, fileName : 'two'},
            {id : 111, fileName : 'three'},
            {id : 222, fileName : 'four'}
          ],
          names : [
            'joe',
            'moe',
            'abe'
          ],
          collection : [
            { title : 'first', 
              things : [
                {thing : 'thing 1'},
                {thing : 'thing 2'},
                {thing : 'thing 3'}
              ]
             },
            { title : 'second', 
              things : [
                {thing : 'thing a'},
                {thing : 'thing b'},
                {thing : 'thing c'}
              ]
             }
          ]
        };
 
 
        var Template = function(html, data) {
          var div = document.createElement('div');
 
          this.isVar = /\s?^\*+/;
          this.isCollection = /^data/;
 
          div.innerHTML = html;
 
          this.traverse(div, data);
 
          document.body.appendChild(div);
        };
 
        Template.prototype = {
          constructor : Template,
          resolveVar : function(path, ctx, index){
            var curr;
            if (path === '*'){
              return ctx;
            }else{ 
              path = path.replace(/^\*/,'').split('.');
              curr = ctx;
 
              for (var i = 0; i < path.length; i++){
                curr = curr[path[i]];
              }
 
              if (curr) {
                return curr;
              } else {
                return false;
              }
            }
          },
 
          traverse : function(parent, scope, index, noChildren){
            var i, j, k, attr, val, varValue, node, tempEl, 
                oldScope, newScope, collection, newHTML, collectionItem;
 
            if (parent.attributes) {
              for (i = 0; i < parent.attributes.length; i++){
                attr = parent.attributes[i];
                if (attr.nodeValue.match(this.isVar)){
                  val = this.resolveVar(attr.nodeValue, scope, index); 
                  if (val === false || val === ''){
                    parent.attributes.removeNamedItem('checked');
                  } else {
                    parent.setAttribute(attr.name, this.resolveVar(attr.nodeValue, scope, index));
                  }
                }
              }
            }
 
            if (!parent.innerHTML) { return; }
 
            if (parent.innerHTML.match(this.isVar)){
              varValue = this.resolveVar(parent.innerHTML, scope, index);
              if (varValue){
                parent.innerHTML = varValue; 
              } 
            }
 
            for (var i = 0; i < parent.childNodes.length; i++){
              node = parent.childNodes[i];
 
              if (node.attributes){
                for(j = 0; j < node.attributes.length; j++){
                  attr = node.attributes[j];
                  if (attr.name.match(this.isCollection)){
 
                    tempEl = document.createElement('div');
                    tempEl.innerHTML = node.innerHTML;
                    oldScope = scope;
                    newScope = attr.name.replace('data-','');
                    collection = scope[newScope];
 
                    if (collection){
                      newHTML = "";
                      node.innerHTML = "";
                      for (var k = 0; k < collection.length; k++){
                        collectionItem = document.createElement('div');
                        collectionItem.innerHTML = tempEl.innerHTML;
 
                        this.traverse(collectionItem, collection[k], k); 
                        newHTML += collectionItem.innerHTML;
                      } 
                      node.innerHTML = newHTML;
                    } 
                    scope = oldScope;
                  }
                } 
 
              }
 
              if (node.childNodes.length > 0) {  
                if (node.nodeType === 3){ return; }
                this.traverse(node, scope, index);
              } else {
                this.traverse(node, scope, index, noChildren);
              }
            }
          }
        };
 
        var template = new Template($('#tmpl').html(), data);
 
      });
    </script>
    <style>
      body,html{
        font-family : sans-serif; 
      }
      .thing{
        border : 1px solid red; 
        padding : 5px;
      }
    </style>
  </head>
  <body> 
    <script id="tmpl" type="text/html">
      <div class="app">
 
        <h2 style="*titleStyle">*title</h2>
 
        <p>*some.nested.prop</p>
 
        <form>
          <input type="checkbox" checked="*checked">
        </form>
 
        <ul data-items>
          <li>*value</li>
        </ul>
 
        <h3>Files:</h3><hr>
        <select data-files>
          <option value="*id">*fileName</option>
        </select>
 
        <h3>Names:</h3><hr>
        <div data-names>
          <b>*</b>
          <div class="name">*</div>
        </div>
 
        <h3>Things:</h3><hr>
        <div data-collection>
          <div class='thing'>
            <h2>*title</h2>
            <div data-things>
              <p>*thing</p>
            </div>
          </div>
        </div>
 
      </div> 
    </script>
  </body>
</html>

So this takes data like this:

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
var data = {
  title : 'cool',
  titleStyle : 'color : red',
  some : { 
    nested : {
      prop : 'you got it'
    }
  },
  checked : false,
  items : [
    {value : 1},
    {value : 2},
    {value : 3}
  ], 
  files : [
    {id : 123, fileName : 'one'},
    {id : 321, fileName : 'two'},
    {id : 111, fileName : 'three'},
    {id : 222, fileName : 'four'}
  ],
  names : [
    'joe',
    'moe',
    'abe'
  ],
  collection : [
    { title : 'first', 
      things : [
        {thing : 'thing 1'},
        {thing : 'thing 2'},
        {thing : 'thing 3'}
      ]
     },
    { title : 'second', 
      things : [
        {thing : 'thing a'},
        {thing : 'thing b'},
        {thing : 'thing c'}
      ]
     }
  ]
};

and a template like this:

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
<div class="app">
  <h2 style="*titleStyle">*title</h2>
 
  <p>*some.nested.prop</p>
 
  <form>
    <input type="checkbox" checked="*checked">
  </form>
 
  <ul data-items>
    <li>*value</li>
  </ul>
 
  <h3>Files:</h3><hr>
  <select data-files>
    <option value="*id">*fileName</option>
  </select>
 
  <h3>Names:</h3><hr>
  <div data-names>
    <b>*</b>
    <div class="name">*</div>
  </div>
 
  <h3>Things:</h3><hr>
  <div data-collection>
    <div class='thing'>
      <h2>*title</h2>
      <div data-things>
        <p>*thing</p>
      </div>
    </div>
  </div>
 
</div>

and renders like this:

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

The real trick here is the collections, that is, when the data has an array of objects this takes the existing nodes out of the element that needs to be the parent of a collection of elements, duplicates it and fills in the values as it goes.

This code needs some refactoring and possibly the addition of document fragments to speed it up a bit. Also there are a couple things that need to be figured out in terms of flexibility of the templates. Like, is it ok to do:

<h2>*variableA is a weird *variableB</h2>

This can get kind of hairy so I might just avoid it, forcing only vars and spaces to be able to be defined inside nodeValues… not sure yet…

<h2>*variableA *variableB</h2>

Next step is to combine this with the Watch class from Part 1 of this post series.

Where Will This Go?

I hope this goes somewhere cool:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var __;
__ = function(){
  return __;
};
__.__ = __;
 
__.__().__.__()().__(__).__(__,__,__);
 
__(__(__.__)().__.__.__.__.__);
 
__.
__.
__()()().__.
__;

but, it will probably go nowhere…

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.