简体   繁体   中英

How to trigger a Client JS method when a subscribed data is changed

I want my app to fire a method (client side) when a particular subscribed data is changed? for example, the client side has this following subscription

Meteor.subscribe('thePlayers');

thePlayers subscription returns a collection of data which is being displayed in the html through the template.

so whenever the collection get changed, Meteor automatically change the data in the HTML also. Besides this feature, I want my app to fire a method say fire() to be executed as soon as data get changed. What should i do to achieve this?

As David Weldon correctly, cursor.observerChanges is the way to go. Here's how you can use it for your example (assuming your collection is called thePlayers ):

client-side

methodCaller = function (methodName) {
  return function (/* arguments */) {
    Meteor.apply(methodName, arguments)
  }
}

var fireCaller = methodCaller('fire')
thePlayers.find().observeChanges({
  added: fireCaller,
  changed: fireCaller,
  removed: fireCaller
})

In case you need this fire() to be run on server , you don't need a method, you can just rely on the observeChanges feature or just observe in your publication. See this question to get an example of how you can achieve that.

In case you need this fire() to be run on client , keep in mind that every helper in your template is reactive, that means it will re-run each time your collection is changed. I assume that it requires that you use the subscription inside it, but that needs to be confirmed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM