backbone.js中的时间间隔

时间:2014-01-22 05:31:58

标签: javascript backbone.js

我需要每5秒执行一次以下功能。我在骨干和javascript工作,我不知道如何实现这一目标。

代码如下:

$(document).ready(function () {
    $.ajaxSetup({
        dataType: 'json',
        xhrFields: {withCredentials: true},
        crossDomain: true
    });
    var a = new ServerCollection();
    var collectionView = new ServerCollectionView({collection:a});
    collectionView.collection.fetchData();
    $("#content").append(collectionView.$el);
});

2 个答案:

答案 0 :(得分:3)

这是一个简单的工作示例http://jsfiddle.net/dLsXj/

这是Backbone代码的工作版本:

function myFunction() {
    // Be sure to `return collection.fetch();` in `fetchData()` method 
    // to wait while collection will be updated
    collectionView.collection.fetchData().done(function() {
        // Run the function next time after 5 sec when collection will be populated
        setTimeout(myFunction, 5000);
    });
}

// We can setup ajax and collection/view without document ready
$.ajaxSetup({
    dataType: 'json',
    xhrFields: {withCredentials: true},
    crossDomain: true
});
var a = new ServerCollection();
var collectionView = new ServerCollectionView({collection:a});

$(document).ready(function () {
    // We need to wait document ready to append element
    $("#content").append(collectionView.$el);

    // Run the function first time without timeout
    myFunction();
});

我之所以使用setTimeout只是因为我们正在使用异步加载。例如,如果我们使用setInterval 5秒,收集将在7秒后加载,这将是不公平的。

快乐的编码!

答案 1 :(得分:0)

var inter = setInterval(function() { ...}, 5000);

....

clearInterval(inter);