I’ve just started learning Meteor and I love it! after a year just developing with node.js + express.js + socket.io I found Meteor very easy and amazing. I’m reading the Discover Meteor book and encountered my first issue when trying to test the latency compensation by adding a delay in the server side code of a method that inserts a document in a collection. The file implementing this method is under /lib/collections folder, so is accessible by both the server and client, however only code for server is run and I don’t understand why.
Here is the code:
Posts=new Mongo.Collection('posts');
Meteor.methods({
postAdd:function(postAttributes){
check(Meteor.userId(),String);
check(postAttributes,{
title:String,
url:String
});
if(Meteor.isServer){
postAttributes.title+=' (server)';
Meteor._sleepForMs(5000);
}else{
postAttributes.title+=' (client)';
}
var posWithTheSameLink=Posts.findOne({url:postAttributes.url});
if(posWithTheSameLink){
return {
postExists:true,
_id:posWithTheSameLink._id
}
}
var user=Meteor.user();
var post=_.extend(postAttributes,{
userId:user._id,
author:user.username,
submitted:new Date()
});
var postId=Posts.insert(post);
return {
_id:postId
};
}
});
For some reason the if(Meteor.isServer)… code works but not the else (Meteor.isClient). This means that when a post is submitted, the client doesn’t show anything until the 5 seconds have passed, while it is supposed to show the stub result meanwhile the server finishes and syncs the data.
The event handler that calls the method is the following (post_add.js):
Template.postAdd.events({
'submit form':function(e){
e.preventDefault();
var post={
url:$(e.target).find('[name=url]').val(),
title:$(e.target).find('[name=title]').val(),
user_id:Meteor.userId
};
Meteor.call('postAdd',post,function(error,result){
if(error) return alert(error.reason);
if(result.postExists) alert('This link has been already posted.');
//Router.go('postPage',{_id:result._id});
});
Router.go('postsList');
}
});
What am I doing wrong?
Thanks.