2013-02-14 99 views
0

我有一个骨干应用程序,它将公告呈现给dom,但是,我希望公告在几秒后消失。我猜测,在显示公告后,我应该调用一个可以将其删除的函数,但有没有办法延迟它的执行,或者在显示模板后创建回调。对不起,如果这是一个简单的问题。javascript flash message

$(this.el).html(this.template({ announcement: announcement})); 

    this.removeAnnouncement(); 
    }, 

    removeAnnounce: function(){ 
    this.$el.remove(); 
    }, 

回答

4

可以使用的setTimeout:

window.setTimeout(_.bind(this.removeAnnounce, this), 2000); 

这将调用this.removeAnnounce2000毫秒(或2秒)。请注意,不要在this.removeAnnounce之后添加(),因为实际上正在传递函数引用。超时将在时间结束后调用该函数。

编辑:_.bind部分确保在范围内的this正确分配超时调用该函数时。谢谢@PaulHoenecke

+1

应该是'window.setTimeout(_。bind(this.removeAnnounce,this),2000);''我认为,因为'removeAnnounce'中的'this'将是没有绑定的'window'。 – 2013-02-14 04:53:39

+0

@PaulHoenecke同意,我只是查找是否有一个干净的方式来绑定backbone.js。你为我节省了大部分的努力。 :) – 2013-02-14 04:56:08

+0

谢谢,为什么我需要窗口前缀? (删除公告功能在同一视图中。)有什么我失踪? – Leahcim 2013-02-14 05:01:25