2

基本上我想要这个设置:

var Game = Backbone.Model.extend({
    defaults: {
    },
    autoSync: true
});

var Games = Backbone.Firebase.Collection.extend({
    url: 'https://<myapp>.firebaseio.com/games',
    autoSync: false,
    model: Game
});

每个游戏都应该与服务器数据自动同步,但我不想听整个 child_* Firebase 系列事件。目标是更新单个项目视图,而不是重新绘制整个列表。

向那里的人们致以亲切的问候和快乐的编码;)

4

1 回答 1

2

您可以使用Backbone.Firebase.Collectionwith autoSyncenabled 更新单个项目。要重新渲染单个项目,您需要在项目触发更改事件时进行监听。Firebase 文档中的 BackboneFire 快速入门中显示了这个概念。

但是,请注意,您不能将 aBackbone.Firebase.Model与 a混合使用Backbone.Firebase.Collection

Todo 模型和集合

在下面的示例中,请注意如何Backbone.ModelBackbone.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,我们听collectionwhich 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);
  }
});
于 2014-12-16T12:55:51.587 回答