Server Side方法在方法调用上抛出错误,但在客户端上不抛出

时间:2014-09-11 10:18:09

标签: meteor

在我的客户端上,我有以下代码

# If clicking on unit while target is set, activates action
  'click .actor': () ->
    character = Meteor.user().character()
    target = Session.get('target')
    skill = Session.get('selectedSkill')

    if target and skill
      console.log character.battle()
      Meteor.call('useSkill', skill, character, target, (err) ->
        if err then console.log err.reason
      )

在这里,当我调用character.battle()时,它会正确返回战斗文档。但是当我在同一个对象上调用相同的方法时,在useSkill()方法中,它会抛出以下错误

Exception while invoking method 'useSkill' TypeError: Object #<Object> has no method 'battle'

Serverside方法

useSkill: (skill, actor, target) ->
    cost = skill.cost

    console.log "battle: #{actor.battle()}"
    ....

和关联'battle()'方法

@Characters = new Meteor.Collection('characters', 
    transform: (entry) ->

        entry.battle = () ->
            Battles.findOne({active: true, $or: [{characterOneId: this._id}, {characterTwoId: this._id}]})

        return entry
)

2 个答案:

答案 0 :(得分:1)

您只能将可序列化对象作为方法参数传递。换句话说,当您像这样传递actor参数时,不会保留在客户端添加的所有自定义方法。要在服务器上访问自定义函数,需要在服务器上创建对象。

因此,不要传递整个character对象,只需传递其_id并在方法中再次找到它:

useSkill: (skill, actorId, target) ->
  actor = Characters.findOne actorId
  ...
  console.log "battle: #{actor.battle()}"

答案 1 :(得分:0)

EJSON不会对函数进行序列化,也不会通过DDP发送。 在Meteor.call字符传递ID:

Meteor.call('useSkill', skill, character._id, target, (err) ->
   if err then console.log err.reason
)

useSkill方法中找到actor:

useSkill: (skill, actorId, target) ->
    cost = skill.cost
    actor = Characters.findOne actorId
    console.log "battle: #{actor.battle()}"