【问题标题】:helper sometimes called twice in meteor js助手有时在流星 js 中调用两次
【发布时间】:2014-12-09 22:39:48
【问题描述】:

我有这个助手,有时第一次调用两次 slug 未定义第二次没问题,如何防止助手被调用两次?

shareurl: ->
    console.log "helper"

    campId = Session.get('campaign_id')

    Meteor.call 'getCampaignSlug', campId, (e, resp) ->
      console.log e if e
      console.log resp
      slug = resp[0]
      campaignId = resp[1]
      Session.set('slug' + campId, slug)

    slug = Session.get('slug' + campId)
    #slug = "test"

    console.log Meteor.absoluteUrl "" + Meteor.user()._id + '/' + slug
    return Meteor.absoluteUrl "" + Meteor.user()._id + '/' + slug

在模板中它被调用了一次。但在控制台中我看到它有时被调用了两次。

<button class="btn btn-primary pull-right draft-send mr10" type="button" data-shareurl="{{shareurl}}" data-step="1" data-intro="Click here to send your campaign" data-position="left">Send</button>

【问题讨论】:

    标签: javascript meteor meteor-helper


    【解决方案1】:

    不熟悉coffeescript,但尝试像这样包装campId = Session.get('campaign_id')

    if(campId = Session.get('campaign_id')){
      //do my stuff
    }
    

    那么如果你的会话变量是未定义的,什么都不会被处理。

    干杯,

    【讨论】:

      【解决方案2】:

      它被调用了两次,因为当它第一次被调用时,你进行了一个方法调用。当处理该方法调用的结果时(注意:此时已返回对该助手的第一次调用),您更改了该助手所依赖的会话变量,因此再次调用该助手。

      [注意]

      那么,这不会导致无限循环吗?不,因为第二次调用助手时,您将会话变量设置为与之前相同的值,这不会导致重新运行。

      [/注意]

      那么解决办法是什么?这可以用不同的方式处理(但恐怕都不是很好),但如果你有一个帮助器返回 Session.get('slug' + Session.get('campaign_id')) 的值,你可以在 #if 块表达式中使用这个帮助器来查看它是否被分配一个值与否,在这个 #if 块表达式中,你调用你的 shareurl

      【讨论】:

        猜你喜欢
        • 2015-09-15
        • 2017-01-10
        • 2018-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        相关资源
        最近更新 更多