gpt4 book ai didi

javascript - Backbone.js 计时器 - 无用的 setInterval 调用

转载 作者:行者123 更新时间:2023-11-29 20:00:53 25 4
gpt4 key购买 nike

虽然我搜索了解决方案,但没有找到适合我的问题的解决方案。我正在使用 cordova 和 jquery mobile。触发事件:document.ready 和 cordova 的设备就绪。我想通过检查 bool 值来检查加载状态,以了解何时启动主应用程序。

看看我的代码:

首先:加载的第一个 js 文件:

function checkReadyStates() {
if(domReady && cordovaReady) {
timer.stop();
start();
}
}

var domReady = false;
var cordovaReady = true;
var timer = new TimerModel({interval : 50, method : checkReadyStates});
timer.start();

// get notified when DOM is loaded
$(document).ready(function() {
ConsoleController.info('Document ready.');
domReady = true;
});

// get notified when cordova is ready
document.addEventListener('deviceready', function() {
ConsoleController.info('Cordova loaded.');
cordovaReady = true;
}, false);

第二个:TimerModel:

define(['backbone'],function(Backbone) {

var model = Backbone.Model.extend({

defaults: {
timerObject : null,
active : false,
interval : 1000,
method : null,
},

// init timer
initialize : function() {
_.bindAll(this, 'start', 'stop'); // context bindings
},

// starts the timer with given interval
start : function() {
if(!this.active) {
this.active = true;
this.timerObject = setInterval(this.method, this.interval);
}
},

// stops timer
stop : function() {
this.active = false;
clearInterval(this.timerObject);
}

});

// return the timer model
return model;

});

希望有人能提供帮助。谢谢!

最佳答案

这行代码在这里

this.timerObject = setInterval(this.method, this.interval);

this.methodthis.interval 都是undefined,所以你没有设置运行 < em>从不。这样做的原因是 Backbone.Model 没有在实例本身的构造函数中定义传递的属性,而是在名为 attributes 的内部属性中定义。您可以使用 model.get(property) 方法访问属性:

this.timerObject = setInterval(this.get('method'), this.get('interval'));

此外,将计时器定义为模型并没有多大意义。毫无疑问,您会让它工作,但这不是 Backbone.Model 的目的。模型用于表示一段数据,而不是功能。我认为一个简单的函数在这里会更好地为您服务。

编辑:换句话说,模型不仅仅是数据,但它们应该包含数据。该模型是定义操作该数据的函数(方法)的好地方。另一方面,您的 TimerModel 是纯逻辑 - 它不代表或封装任何数据或状态。我觉得把逻辑封装成一个简单的函数“类”比较好:

var Timer = function(options) {
options = options || {};
this.active = false;
this.interval = options.interval || 1000;
this.method = options.method || null;


// starts the timer with given interval
this.start = function() {
if(!this.active) {
this.active = true;
this.timerObject = setInterval(this.method, this.interval);
}
};

// stops timer
this.stop = function() {
this.active = false;
clearInterval(this.timerObject);
};

_.bindAll(this, 'start', 'stop')
});

用法:

var timer = new Timer({interval: 50, method:checkReadyStates});

关于javascript - Backbone.js 计时器 - 无用的 setInterval 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14600709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com