订阅完成后如何在客户端上运行方法 [英] How to run method on client when subscribe is complete

查看:72
本文介绍了订阅完成后如何在客户端上运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的设置:

//in global.js file
items = new Meteor.Collection("items");

//on server in main.coffee
Meteor.publish "nearItems", (lat, lng) ->
  return items.find( { loc : { $near : [lng, lat] } })

//on client in map.coffee
Meteor.autosubscribe -> 
  Meteor.subscribe( "nearItems", 37.78, -122.416, addMarkers)

addMarkers = ->
  places = items.find().fetch()
  console.log "Adding this many markers:", items.length 
  for item, i in places
    theLatLng = new google.maps.LatLng(item.loc[1], item.loc[0])
    addMarker theLatLng, map, item 
  return

当客户端获取数据时,如何调用方法addMarkers。

How do I call the method addMarkers when the client gets the data.

文档说我需要调用ready方法 http ://docs.meteor.com/#meteor_publish 但是对于我当前的设置,我不确定如何执行此操作,因为我无法在return语句之前调用ready,因为它还没有准备好。

The docs say I need to call the ready method http://docs.meteor.com/#meteor_publish but with my current setup I am unsure how to do this as I can't call ready before the return statement because it won't be ready yet.

Meteor.publish语句工作正常,我得到了客户端上的所有项目。但是加载需要几秒钟。所以我需要一种方法来等待项目集合包含来自服务器的所有数据。我可以打开javascript控制台,等待几秒后,在地图上正确调用addMarkers和最接近的100显示。

The Meteor.publish statement is working correctly and I get all the items on the client. But it takes a few seconds to load. So I need a way to wait until the item collection has all the data from the server. I can open the javascript console and after waiting a few seconds call addMarkers and the nearest 100 display correctly on the map.

我尝试设置Deps.autorun(runFunc)请参阅 http://docs.meteor.com/#deps_autorun ,但无论出于何种原因,它都会显示收集项目不存在。

I tried setting up a Deps.autorun(runFunc) see http://docs.meteor.com/#deps_autorun but for whatever reason it says the collection items doesn't exist.

推荐答案

我不知道为什么在使用 autorun <时出现错误/ code>。如果您粘贴有问题的代码,也许我可以提供帮助。我处理这个问题的方法是:

I don't know why you get the error while using autorun. Maybe I can help if you paste the problematic code. The way I handle this issue is:

Meteor.autorun( =>
  sub = Meteor.subscribe("collection", param1, param2)

  if sub.ready()                  # Ready is reactive. Once it changes 
                                  # the computation is invalidated

    addMarkers()                  # Now the data is at the client
    Session.set("loading", false) # Do your main thing based on "loading"
  else
    Session.set("loading", true)  # Do some reactive waiting based on "loading"
)

这篇关于订阅完成后如何在客户端上运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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