학습 목적으로 간단한 백본 앱을 만들고 있습니다. 나는 시간과 날짜를 표시하고있다. 디스플레이는 적어도 1 분마다 업데이트되어야합니다. 모델에 "시간",보기에 "시간보기"를 사용하고 있습니다. 내 첫 번째 질문은 일종의 철학적이며 setInterval, Model 또는 View를 보유하고 있습니까? Model은 자체 업데이트해야한다고 생각하지만 작동하도록 코드를 가져올 수 없습니다. 모델을 업데이트하는 것처럼 보이지만 model.update()를 view.render() 함수에 바인딩하면 작동하지 않습니다.Backbone.js 모델, setInterval을 올바르게 추가합니다.
아래 코드에서 setInterval을보기로 전환하고 다른 시도를 주석 처리했습니다. 비록 이것이 작동하더라도 (그리고 아마도 은이 모델의 업데이트를 제어해야 함) this.model.bind ('update', this.render)는 작동하지 않으며 렌더링을 별도로 시작해야합니다. .
var Time = Backbone.Model.extend({
initialize: function(){
_.bindAll(this, 'update', 'startLoop', 'stopLoop');
//this.startLoop();
this.update();
},
startLoop: function(){
this.update();
this.interval = window.setInterval(_.bind(this.update, this), 10000);
},
stopLoop: function(){
this.interval = window.clearInterval(this.interval);
},
update: function(){
var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
var date = new Date();
var tHour = date.getHours();
if(tHour < 12){ if(tHour == 0) tHour = 12 } else { tHour = tHour-12 };
tHour = tHour.toString();
var tMin = date.getMinutes();
tMin = (tMin < 10) ? '0' + tMin.toString() : tMin.toString();
this.set({
hour : tHour,
ampm : (date.getHours() < 12) ? "am" : "pm",
minute : tMin,
day : days[ date.getDay() ],
month : months[ date.getMonth() ],
date : date.getDate(),
year : date.getFullYear()
});
}
});
var TimeView = Backbone.View.extend({
el: '#time-date-display',
interval: 0,
template: $('#tpl-time-date').html(),
initialize: function(){
_.bindAll(this, 'render');
this.model = new Time();
this.render();
//this.model.bind('update', this.render);
this.interval = window.setInterval(_.bind(function(){ this.model.update(); this.render();}, this), 10000);
},
render: function(){
//alert('TimeView.render()');
$(this.el).html(
_.template(this.template, this.model.toJSON())
);
}
});
$('body').append(_.template($('#tpl-time-weather-display').html()));
var tv=new TimeView();
도움 주셔서 감사합니다. 어떻게 든 모델에 함수 호출을 바인딩 할 수 있다는 것을 내 머리 속에서 알게되었습니다. –
예. 임의의 이벤트에 바인드 할 수 있습니다. 예를 들어'model.trigger ('update')'를 할 수는 있지만이 동작에 대한 좋은 유스 케이스는 아닙니다. –