发布任意数据并自动更新 HTML [英] Publish arbitrary data and automatically update HTML

查看:19
本文介绍了发布任意数据并自动更新 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何发布任意数据?这就是我想要完成的,提供以下模板:

How do I publish arbitrary data? This is what I want to accomplis, giving the following template:

<head>
  <title>Test</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <h1>{{greeting}} World!</h1>
</template>

我想使用 Meteor.setInterval 按设定的时间间隔动态更新 greeting.文档中的所有示例似乎都是关于 Collections 的.

I would like to dynamically update greeting on set intervals, using Meteor.setInterval. All examples in the documentation seems to be about Collections though.

推荐答案

您可以使用 Meteor Session 变量作为响应式数据源,以便模板自动重新渲染 (http://docs.meteor.com/#session_set).试试这个:-

You could use a Meteor Session variable as a reactive data source so the template automatically re-renders (http://docs.meteor.com/#session_set). Try this:-

if (Meteor.is_client) {

  // Use 'greeting' Session variable as a reactive data source
  Session.set('greeting', 0);

  Template.hello.greeting = function () {
    return "Welcome to test: " + Session.get('greeting');
  };

  Meteor.setInterval(function() {
    Session.set('greeting', Session.get('greeting') + 1);
  }, 1000);
}

if (Meteor.is_server) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

更新: 显示与 streams 包的挂钩.示例有效,但使用后果自负

Updated: To show hooking into streams package. Example works but use at your own peril

if (Meteor.is_client) {
  // Use client from stream package
  sc = new Meteor._Stream('/sockjs');
  sc.on('message', function(payload) {
    var msg = JSON.parse(payload);

    // Set session variable so template reacts
    Session.set('greeting', JSON.stringify(msg.data));
  });

  // Use 'greeting' Session variable as a reactive data source
  Template.hello.greeting = function () {
    return Session.get('greeting');
  };
}

if (Meteor.is_server) {
  // Use server from stream package
  ss = new Meteor._StreamServer();

  // register handler for socket connection
  ss.register(function (socket) {
    var data = {socket: socket.id, connected: new Date()}
    var msg = {msg: 'data', data: data};

    // Send message to all sockets
    _.each(ss.all_sockets(), function(socket) {
      socket.send(JSON.stringify(msg));
    })
  });
}

这篇关于发布任意数据并自动更新 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆