您可以使用Backbone.Firebase.Collection
with autoSync
enabled 更新单个项目。要重新渲染单个项目,您需要在项目触发更改事件时进行监听。Firebase 文档中的 BackboneFire 快速入门中显示了这个概念。
但是,请注意,您不能将 aBackbone.Firebase.Model
与 a混合使用Backbone.Firebase.Collection
。
Todo 模型和集合
在下面的示例中,请注意如何Backbone.Model
在Backbone.Firebase.Collection
. autoSync
默认情况下已启用该集合。
// A simple todo model
var Todo = Backbone.Model.extend({
defaults: { title: "New Todo" }
});
// Create a Firebase collection and set the 'firebase' property
// to the URL of your Firebase
var TodoCollection = Backbone.Firebase.Collection.extend({
model: Todo,
url: "https://<your-firebase>.firebaseio.com"
});
待办事项视图
下面的示例是单个待办事项的视图。在initialize
函数内部,该listenTo
方法用于侦听模型的change
事件。change
每次远程或本地更新模型时都会触发该事件(远程保持更改)。
// A view for an individual todo item
var TodoView = Backbone.View.extend({
tagName: "li",
template: _.template("<%= title %>"),
initialize: function() {
// whenever the model changes trigger a re-render of the single view
this.listenTo(this.model, "change", this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});
渲染列表
通过TodoView
设置,列表也可以轻松呈现。在下面的initialize
函数中AppView
,我们听collection
which will be a TodoCollection
。每当将一个项目添加到集合中时,addOne
就会执行该函数。该addOne
函数只是将一个新的附加TodoView
到页面。
// The view for the entire application
var AppView = Backbone.View.extend({
el: $('#todoapp'),
initialize: function() {
this.list = this.$("#todo-list"); // the list to append to
// by listening to when the collection changes we
// can add new items in realtime
this.listenTo(this.collection, 'add', this.addOne);
},
addOne: function(todo) {
var view = new TodoView({model: todo});
this.list.append(view.render().el);
}
});