【问题标题】:Running a function AFTER a meteor template is updated在更新流星模板后运行函数
【发布时间】:2015-04-21 07:49:36
【问题描述】:

我有一个流星模板呈现一些我需要在其上执行 jquery 功能的 html。现在,我已经设置了一个依赖项,以便每次与该模板相关的数据(对象列表)发生更改时,该函数都会运行。我完全不确定这是做我想做的事情的最佳方式,但是每次我添加/删除/重新排列对象时它都会运行该函数,所以这是一个开始。

然而,该函数似乎在重新渲染模板之前运行,因此前一组块得到 jquery-fied,但我刚刚在该操作中添加的任何块都没有.

有没有办法强制函数在模板被渲染/更新后运行?非常感谢任何帮助!

(这里有类似的问题——Meteor reactive jquery——但没有任何答案)

以下是一些可能相关的代码位:

Template.showPictures.rendered =
    Deps.autorun () ->
      album = Albums.findOne(Session.get("selectedAlbum"))

      if (album)
        pictures = album.orderedPictures()
        MyApp.loadJQuery()

Template.showPictures.helpers
  pics: ->
    MyApp.myDependency.depend()

    album = Albums.findOne(Session.get("selectedAlbum"))
    album.orderedPictures()

(为什么在我的 Template.rendered 东西中自动运行?不确定。这似乎是一个不错的放置位置,但这是我第一次真正处理依赖关系,所以我可能在这里完全脱离基础。任何关于出了什么问题的任何想法都会非常好。)

【问题讨论】:

    标签: jquery meteor coffeescript meteor-blaze


    【解决方案1】:

    您可以为此使用Tracker.afterFlush(而TrackerDeps 的新名称):

    Template.showPictures.rendered =
        Tracker.autorun () ->
          album = Albums.findOne(Session.get("selectedAlbum"))
    
          if (album)
            Tracker.afterFlush ->
                // This will get executed when (among other things)
                // the UI has been updated.
                pictures = album.orderedPictures()
                MyApp.loadJQuery()
    

    然而,Meteor 方式更像是这样的:

    <template name="things">
        {{#each things}}
            {{> thing}}
        {{/each}}
    </template>
    
    <template name="thing">
        <!-- Show the thing here... -->
    </template>
    
    Template.things.helpers({
        things: function(){
            return Things.find()
        }
    })
    
    Template.thing.rendered = function(){
        // This get executed each time a new thing is rendered!
    }
    

    【讨论】:

      【解决方案2】:

      我找到了一些可行的方法,但它仍然看起来有点 hacky...

      我最终做的是设置超时。所以现在,我没有上面的代码,而是:

      Template.sitePreview.rendered = () ->
        Deps.autorun () ->
          album = Albums.findOne(Session.get("selectedAlbum"))
      
          if (album)
            pictures = album.orderedPictures()
            setTimeout MyApp.loadJQuery, 500
      

      到目前为止,模板渲染/更新的时间已经足够了,因此 JQuery 可以在所有最新数据上运行。仍然希望有一个更优雅的解决方案,但这会做!

      【讨论】:

        猜你喜欢
        • 2015-07-12
        • 1970-01-01
        • 1970-01-01
        • 2012-06-16
        • 2013-09-17
        • 1970-01-01
        • 2012-11-13
        • 2017-10-16
        • 1970-01-01
        相关资源
        最近更新 更多