2016-02-15 64 views
1

我试图通过在集合中插入文档的方法的服务器端代码中添加延迟来测试延迟补偿。这个想法是,当方法在客户端运行“镜像”时,插入的帖子的标题将连接“(客户端)”,然后当该方法在服务器中运行时,它将具有“(服务器)“连接到其标题。由于我为服务器设置了5秒的延迟时间,因此我应该看到帖子标题更改,以证明延迟补偿如何工作。客户端不工作的方法客户端和服务器可以访问流星

我已实施此方法的文件正在/lib目录/收藏夹,所以它应该是由服务器端和客户端都可以访问,但它不工作,我从来没有看到“(客户端) “标题中的文字,只有”(服务器)“,并且该帖子在5秒后才显示出来,所以看起来客户端代码不工作,只有服务器端代码。

这是文件的来源(/lib/collections/post.js)其中所述方法被定义:

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 
     }; 
    } 
}); 

而这是该文件(/客户端/模板的源/postAdd.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'); 
    } 
}); 

如果我添加在post.js文件后立即以下:

if(Meteor.isClient){ alert('This is the client!'); } 

我看到消息雨后春笋般冒出来,所以post.js文件是由客户端definetely访问。

看来方法定义内的任何客户端代码都不起作用。

我在做什么错?

谢谢。

+0

在附注中,我写了一个包来防止这种类型的黑客行为。它被称为['lag-console'](https://atmospherejs.com/alon/lag-console),并允许您延迟发布和方法调用。 – MasterAM

回答

0

作为Meteor的初学者,我想知道同样的事情。

我发现了一些关于Method Life-Cycle的信息,您可能会发现它有用,here

而且我试着运行代码的简化版本:

DB = new Mongo.Collection('db'); 

Meteor.methods({ 
    'test': function(data) { 
    if (Meteor.isServer) { 
     data.title += ' (server)'; 
     Meteor._sleepForMs(50000); // here I increased the delay just to be sure 
    } else { 
     data.title += ' (client)'; 
    } 

    DB.insert(data); 
    if (this.isSimulation) { // logged the output before server response came 
     console.log(DB.find().fetch()); 
    } 
    if (Meteor.isServer) { 
     console.log(DB.find().fetch()); 
    } 
    } 
}); 

这给了我预期的输出。我从浏览器中获得了(client)输出,数据已被插入到客户端数据库中,但未插入到服务器端数据库中。一旦服务器端数据库获得新数据,我的客户端文档自动更改为(server)