How to run method on client when subscribe is complete

浪尽此生 提交于 2019-12-23 04:52:40

问题


Here is my setup:

//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

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

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.

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.

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.


回答1:


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"
)


来源:https://stackoverflow.com/questions/16091885/how-to-run-method-on-client-when-subscribe-is-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!