2012-07-30 60 views
2

嗨,我正在使用backbone.js paly2.0框架应用程序(与Java)。在我的应用程序中,我需要定期从数据库中获取表格数据(对于显示即将发生的事件列表的用例,以及是否应该从列表中删除旧事件)。我正在获取要显示的数据,但是问题是经常打数据库。为此,我尝试按照这些链接使用backbone.js轮询概念Polling a Collection with Backbone.js,http://kilon.org/blog/2012/02/backbone-poller/。但他们没有从db中轮询最新的集合。请建议我如何实现这个或其他选择? 谢谢你。如何在backbone.js中进行轮询?

+2

你是什么意思与_“他们不是从数据库查询最新系列” _。骨干将使用您的服务器发送的数据,如果发送的数据不是您期望的问题可能在服务器端。 – fguillen 2012-07-30 09:39:50

+0

谢谢你的回复.server正在发送数据,我的意思是说我要定期用1分钟的时间打数据库 – 2012-07-30 10:43:11

回答

8

有没有一种原生的方式与骨干做到这一点。但是,你可以实现长轮询请求添加一些方法到您的收藏:

// MyCollection 
var MyCollection = Backbone.Collection.extend({ 
    urlRoot: 'backendUrl', 

    longPolling : false, 
    intervalMinutes : 2, 
    initialize : function(){ 
    _.bindAll(this); 
    }, 
    startLongPolling : function(intervalMinutes){ 
    this.longPolling = true; 
    if(intervalMinutes){ 
     this.intervalMinutes = intervalMinutes; 
    } 
    this.executeLongPolling(); 
    }, 
    stopLongPolling : function(){ 
    this.longPolling = false; 
    }, 
    executeLongPolling : function(){ 
    this.fetch({success : this.onFetch}); 
    }, 
    onFetch : function() { 
    if(this.longPolling){ 
     setTimeout(this.executeLongPolling, 1000 * 60 * this.intervalMinutes); // in order to update the view each N minutes 
    } 
    } 
}); 

var collection = new MyCollection(); 
collection.startLongPolling(); 
collection.on('reset', function(){ console.log('Collection fetched'); }); 
+0

只需要注意触发你自己的''collectionFetched''可能是不需要的,因为它会触发''重置'已经,而且无论如何,这将更加普遍有用。 – loganfsmyth 2012-07-31 02:34:57

+0

我同意,我可以更新它。 :D的感觉是一样的,谢谢! – 2012-07-31 02:59:19