具体的には、標準が<table>
あり、新しいデータが出入りするたびに行を更新したいと考えています。私のデータは JSON オブジェクトとして取得され、新しいアイテムがそこにある場合は、テーブルの対応する場所に行を追加したいと考えています (つまり、順序が重要です)。アイテムがそこにない場合は、削除したい<tr>
。
助けてくれてありがとう。
具体的には、標準が<table>
あり、新しいデータが出入りするたびに行を更新したいと考えています。私のデータは JSON オブジェクトとして取得され、新しいアイテムがそこにある場合は、テーブルの対応する場所に行を追加したいと考えています (つまり、順序が重要です)。アイテムがそこにない場合は、削除したい<tr>
。
助けてくれてありがとう。
http://jsfiddle.net/CoryDanielson/phw4t/
ほら、コードが従うのに十分単純であることを願っています... Backbone.jsクロック。
基本的には、コレクションをビュー内に配置するという考え方です。次に、 a を使用して定期的にコレクションにデータを取得させ、setInterval
.fetch({ 'reset': true }) を呼び出しreset
て、コレクションに新しいデータ セットが含まれるとイベントがトリガーされるようにします。ビューにコレクションのreset
イベントをリッスンさせてから、テーブルをレンダリングします。
どのデータが変更され、どのデータが削除され、どのデータが追加されたかを把握しようとする代わりに、データを再レンダリングする方がはるかに簡単です。難しい方法で行うか、テーブル全体を再レンダリングするだけで、同じ結果になります。DOM 挿入を最適化している限り (DOM への書き込みは 1 回のみ... オフスクリーンでレンダリング)、パフォーマンスに影響はありません。
var PollingCollection = Backbone.Collection.extend({
url: "path/to/data/source",
model: new Backbone.Model(),
initialize: function (model, options) {
this.options = options;
setInterval(function () {
this.fetch({
"reset": true
});
}.bind(this), options.pollRate);
},
/**
* Overriding fetch for the example. If the URL was valid, delete the fetch
* function below.
*/
fetch: function () {
this.reset([
new Backbone.Model({
"name": "current",
"time": Date().toString()
}),
new Backbone.Model({
"name": "next fetch",
"time": "in " + this.options.pollRate / 1000 + " second(s)"
})]);
}
});
var TableView = Backbone.View.extend({
initialize: function (options) {
this.pollingCollection = new PollingCollection(null, options);
this.listenTo(this.pollingCollection, 'reset', this.render);
/**
* appending to body from within a view is 'bad'. normally another
* view would place this in the HTML. Just keepin' it simple for
* example
*/
$('body').append(this.$el);
},
render: function () {
// Render html into table then append. 1 DOM insert.
var table = $("<table></table>"),
html = this.renderTable();
table.append(html);
this.$el.html(table);
},
renderTable: function () {
var tableRows = "";
this.pollingCollection.each(function (model) {
tableRows += this.renderRow(model);
}, this);
return tableRows;
},
renderRow: function (model) {
return "<tr><td>" + model.get('name') + ":</td><td>" + model.get('time') + "</td></tr>";
}
});
var tableView = new TableView({ "pollRate": 1000 }); // fetch data every 1000 ms