-
Notifications
You must be signed in to change notification settings - Fork 4
/
arrays.html
58 lines (48 loc) · 1.53 KB
/
arrays.html
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
<!DOCTYPE html>
<html>
<head>
<link href="prism.css" rel="stylesheet" />
<link href="index.css" rel="stylesheet" />
<script src="../../dist/supermodels.js"></script>
<script src="examples.js"></script>
<script class="code">
// Schemas can be a simple array.
// Here we define a "percentages"
// schema that defines an array of
// numbers in the range 0 -- 100.
var modelSchema = [{
__type: Number,
__validators: [function(value, key) {
if (!value || value < 0 || value > 100) {
return 'Array item ' + key + ' should be between 0 and 100';
}
}],
}];
// Create constructor from the schema
var Model = supermodels(modelSchema);
// Create an instance of the array
var percentages = new Model();
// Add some listeners
percentages.on('push', logEvent);
percentages.on('splice', logEvent);
percentages.on('unshift', logEvent);
// Push some values
percentages.push(80);
console.log(percentages.length); //=> 1
console.log(percentages.errors); //=> []
percentages.push(-10);
console.log(percentages.length); //=> 2
console.log(percentages.errors); //=> ['Array item 1 should be between 0 and 100']
// Any naughty items that enter the array via
// push, splice, unshift etc. will be
// cast to a Number.
percentages.splice(1, 0, '42', '76', '87');
console.log(percentages);
</script>
</head>
<body>
<pre class="language-javascript"><code class="language-javascript"></code></pre>
<script src="index.js"></script>
<script src="prism.js"></script>
</body>
</html>