【问题标题】:How to run method on client when subscribe is complete订阅完成后如何在客户端上运行方法
【发布时间】:2013-04-18 19:53:12
【问题描述】:

这是我的设置:

//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方法。

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

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

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

【问题讨论】:

    标签: javascript meteor publish-subscribe


    【解决方案1】:

    我不知道为什么您在使用 autorun 时会收到错误消息。如果您粘贴有问题的代码,也许我可以提供帮助。我处理这个问题的方式是:

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

    【讨论】:

    • 谢谢!使用你的模型似乎可以解决它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多