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

查看:149
本文介绍了发布任意数据并自动更新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变量用作反应性数据源,以便模板自动重新呈现(

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天全站免登陆