Real-time development framework Meteor API interpretation series & lt; 3 & gt; Publish and Subscribe-(1)

Source: Internet
Author: User


  1. This blog focuses on publish and subscribe.
  2. The meteor version used is
  3. This blog is a simple introduction to subscribe and publish in Meteor.
  4. Repeat the old saying and try to focus on official documents as much as possible.
  5. It is inevitable that this blog is incorrect. If you find it, I hope to point it out.
  6. This blog involves another Collection of knowledge points, which will be described as an independent blog.

It mainly controls how the server pushes data to the client, and if the client receives a dataset

Publish Server

First, you should remove the default autopublish package of meteor before you experiment with this function.

meteor remove autopublish

This package automatically pushes all the datasets you have defined to the client. One advantage of doing so is to make it easier for new users to get started with meteor, because it does not require more configuration and does not need to process publish and subscibe functions. The natural advantage is relative. In the actual development process, data permissions and other aspects require us to precisely control the datasets obtained by the client. This is what publish and subscribe need to implement.


Before pushing a dataset, you must first define a dataset, that is, connect to a dataset in mongodb. If the dataset does not exist, an empty dataset is automatically created. Defining a dataset is simple:

PeopleCollection = new Meteor.Collection("people");

Note thatpeopleIs the name of the dataset in mongodb. After initializing the application, you can connect to mongodb and use shell to check whether the dataset exists. Because this dataset will be used on both the client and the server, make sure that this definition is located outside the server and client folders (not to mention other public, the role of folders in the previous blog (<2>) ). My approach is to createconllection.jsUsed to declare a dataset. HerePeopleCollectionThe object can operate on thispeopleDataset. Note that because the DataSet objectPeopleCollectionIs used at the same time on the client and server, so make sure that you do not addvarThis involves the scope of Meteor. For various reasons, I will write a blog post. Here, I will mention it a little.varThe Defined variables only exist in the file scope. Cross-file unavailability. This is different from Javascript in general html. In addition, when naming a DataSet object, we recommend that you use special words for variables to distinguish them from other types of variables, and avoid repeated names of variables inadvertently. My personal habit is that a DataSet object ends with a Collection, for example, XXXCollection.


The publish function is used on the server. It is described as follows:

Publish (name, func) // name: name of the dataset, data type string, required. // Func: a callback function that controls the content of the dataset published to the client or processes the data twice. It can accept one or more parameters from the client. Of course, the function itself this also has some other attributes. As mentioned later.

It is not as clear as a piece of code. Note that every time before the code, I will mark the file organization structure format|--Indicates the directory of the next layer. To-Indicates the application root directory. Fold is used to represent folders and file is used to represent files. (In fact, a folder with a suffix is a file without a suffix)

---server #fold    |-- startup.js #file    |-- publish.js #file--collection.js #file

Collctions. js

Lelecollection = new Meteor. Collection ("people"); ### declare a dataset

Startup. js initializes some data. It doesn't matter if you don't understand what the function is. Later blogs will talk about it. Here we add some data to the people dataset in mongodb at startup so that we can test the demo.

Meteor. startup (function () {// when the application starts, initialize some data into the people set if (lelecollection. find (). count ()! = 0) {return;} // The lelecollection here uses collections. the dataset operation object defined in js var records les = [{name: "A", address: "Changsha", phone: "111" },{ name:" B ", address: "Changde", phone: "222" },{ name: "small C", address: "Hengyang", phone: "333" },{ name: "Small D", address: "hengnan", phone: "444" },{ name: "small E", address: "Zhuzhou", phone: "555"}]; for (var I = 0; I <les. length; I ++) lelecollection. insert (distinct les [I]);});

Publish. js

// The first parameter of the set to be released to the client is the set name. This parameter is optional. However, we generally use the same name as the set defined in the background, if '''new Meteor. collection ("people") ''' uses people, so people is also used here ;. Of course, for the sake of confidentiality and security, you can obtain them at will. We will test and add a suffix _ safe. You only need to ensure that the returned result set is the one you want to return. // The second parameter is a function. This function can be used when the client needs to pass in parameters. There can be multiple parameters, not limited to the two Meteor parameters in the current example. publish ("people_safe", function (arg1, arg2) {console. log (arg1 + ar2); console. log (arguments); return PeopleCollection. find ({})});

Run this demo now.

Meteor remove autopublish # first remove the automatic data push package to meteor # Run meteor

Open the browser after startuphttp://localhost:3000/There is nothing on the interface. It doesn't matter. We didn't add anything above. That's it. Now, open the chrome console. The previous blog mentioned how to use the console. Input


Returns an empty array. This is because we have pushed data on the server, but we have not subscribed to the data on the client. Therefore, the client does not have any data. Now let's look at the client's subscription data function. Close the browser and stop the application.

Subscribe Client

It mainly refers to subscription settings to receive data from the server.

Meteor. subscribe (name [, arg1, arg2,...] [, callbacks]) name: sets the data set to be pushed by the server definition. That is, what is the first parameter in Meteor. publish, so what should you use when you accept the data pushed by the publish. Required. [Arg1, arg2,...] is an optional parameter. The second parameter callback function that is used to pass to the publish function on the server side as a parameter. It's a little wordy. It's very clear when you look at the code. Callbacks is a callback function that can be executed after the client obtains the data.
Check the code. The application structure is: (a folder is added)
--server #fold    |-- startup.js #file    |-- publish.js #file--client #fold    |-- subscribe.js--collection.js #file

Subscribe. js

// Here two parameters are passed to Meteor. subscribe ("lele_safe", 1, "hello world", function () {console. log ("Data subscription completed ");});

Restart the application.
At this time, when the browser is not accessed, there is no output, because there is no client, now open the browser to access the applicationhttp://localhost:3000/ 
At this time, the server will immediately see the printed parameters passed in. Open the browser console and you will also see that the subscribe callback function is executed.
Then we run it again on the browser Console (Tip: you can press the up and down arrow keys to bring up the input history to avoid entering it every time)


Data is printed.

This section briefly introduces the data definition, push, and subscription processes. For more details, I will describe it in the next blog.
The source code can be downloaded at

Source code instructions: Because the packaged Source Code does not contain mongodb database files (these files are too large, so they are not packaged), you need to perform some operations before the code can run properly. download the compressed file and decompress it. 2. create a project in your working directory, for example, meteor create api003, go to the api003 directory, and cut the. meteor folder to the decompressed folder. Note that in linux and mac,. meteor may be hidden. You can use ctrl + H to display it. Windows is not hidden. This can be run. If you have any questions, please leave a message below the blog

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.