forked from DiscoverMeteor/DiscoverMeteor_De
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06s-reactivity.md.erb
107 lines (76 loc) · 1.4 KB
/
06s-reactivity.md.erb
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
---
title: Reactivity
slug: reactivity
date: 0006/01/02
number: 6.5
sidebar: true
contents: Learn about Meteor's reactive code dependency system.|Understand the motivations and how it makes code declarative.|Learn to use advanced code that uses reactive data.
paragraphs: 20
---
////
////
////
////
~~~js
Posts.find().observe({
added: function(post) {
// when 'added' callback fires, add HTML element
$('ul').append('<li id="' + post._id + '">' + post.title + '</li>');
},
changed: function(post) {
// when 'changed' callback fires, modify HTML element's text
$('ul li#' + post._id).text(post.title);
},
removed: function(post) {
// when 'removed' callback fires, remove HTML element
$('ul li#' + post._id).remove();
}
});
~~~
////
<% note do %>
### When *Should* We Use `observe()`?
////
////
<% end %>
### A Declarative Approach
////
////
////
~~~html
<template name="postsList">
<ul>
{{#each posts}}
<li>{{title}}</li>
{{/each}}
</ul>
</template>
~~~
////
~~~js
Template.postsList.helpers({
posts: function() {
return Posts.find();
}
});
~~~
////
### Dependency Tracking in Meteor: Computations
////
////
////
////
////
### Setting Up a Computation
////
~~~js
Deps.autorun(function() {
console.log('There are ' + Posts.find().count() + ' posts');
});
~~~
////
~~~js
> Posts.insert({title: 'New Post'});
There are 4 posts.
~~~
////