问题
I am trying to do a simple prototype using Meteor (I am very new to Meteor).
I have the following in an isClient block
Template.imageList.helpers({
images: function() {
return Images.find({});
},
}
);
Then for quick demo purposes I am inserting data with meteor mongo and the following
db.images.insert({ imgSrc: "http://mysite/img1.png", createdAt: new Date() })
This works and I can see the change reflected on the ui but I need to also run a client side javascript function when this occurs. I have been trying things like pub/sub and Tracker but can't get anything to work.
Any guidance would be great.
回答1:
Use observeChanges
:
Images.find().observeChanges({
added: function (id, fields) {
runFunction();
},
changed: function (id, fields) {
runFunction();
},
removed: function (id) {
runFunction();
}
});
See here for more: http://docs.meteor.com/#/full/observe_changes
回答2:
Using meteor-collections-hooks its the more easy way to accomplish this.
meteor add matb33:collection-hooks
For example.
Images = new Mongo.Collection('Images')
example = function(){
console.log("updated")
}
if (Meteor.isClient) {
Images.before.update(function(userId, doc, fieldNames, modifier, options){
example();
})
}
the example()
function will run each time the Images collection
get updated.
回答3:
Run function on the client's template helper, like:
Template.imageList.helpers({
images: function() {
imgs = Images.find({});
yourFunction();
return images;
}
});
Or use Tracker.autorun
wrapper:
Tracker.autorun(
Images.find({});
yourFunction();
)
来源:https://stackoverflow.com/questions/29596256/meteor-run-a-function-when-a-mongo-collection-gets-updated