学習目的でシンプルなバックボーンアプリを作成しています。時刻と日付の表示を作成しているだけです。表示は少なくとも1分ごとに更新する必要があります。モデルには「Time」、ビューには「TimeView」を使用しています。私の最初の質問は、setInterval、Model、またはViewを保持する一種の哲学的なものですか?モデルは自己更新する必要があると思いますが、コードを機能させることができませんでした。モデルを更新しているように見えますが、model.update()のview.render()関数へのバインドは機能しません。
以下のコードでは、setIntervalをViewに切り替えて、他の試みをコメントアウトしました。これは機能しますが(おそらくビューがモデルの更新を制御する必要があります)、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();