带有 Mongoose/Express 的 Backbone.js。
我很难理解如何与服务器上的数据库和模型进行通信。老实说,我不了解模型和服务器的关系。客户端上的模型是否与服务器上的模型同步?服务器上还有模型吗?目前在 MongoDB 中有填充数据,我要做的就是让 fetch() 工作。任何帮助都会很棒。当 Backbone 已经完成所有这些操作时,我试图避免使用 RESTful 调用。
// CLIENT
// Lobby.js
(function($){
var socket = io.connect('http://localhost:3000');
var App = Backbone.Router.extend({
routes: {
'': 'lobby'
},
lobby: function () {
var collection = new Collection();
var listView = new MatchListView(collection);
collection.fetch();
collection.fetch({success: function(){
console.log("Fetch Success"); // => 2 (collection have been populated)
}});
}
});
var Model = Backbone.Model.extend();
/**
* Collection - bound to the server
* matchListView is listening for event changes
*/
var Collection = Backbone.Collection.extend({
url: 'lobby',
socket:socket,
model: Model,
initialize: function(Collection){
_.bindAll(this, 'addOne', 'removeOne', 'removeOne');
this.ioBind('createMatch', this.addOne, this);
this.ioBind('removeMatch', this.removeOne, this);
},
addOne: function(data) {
this.add({id:data._id});
},
removeOne: function(data) {
console.log('remove match ' + data._id);
this.remove({id:data._id});
}
});
/**
* View - bount to collection
* listening for changes to collection 'add' and 'remove'
*/
var MatchListView = Backbone.View.extend({
el: $('body'),
urlRoot: 'lobby',
socket:socket,
events: {
'click #create': 'createMatch'
},
initialize: function(Collection){
_.bindAll(this, 'render', 'renderCollection','addOne', 'removeOne', 'createMatch');
this.collectionView = Collection;
this.collectionView.bind('add', this.addOne);
this.collectionView.bind('remove', this.removeOne);
this._viewPointers = {}; // make sure we're starting over
this.render();
},
render: function(){
...
}
});
$(document).ready(function ()
{
// create a new app and trigger the router.
window.app = new App();
Backbone.history.start();
});
})(jQuery);
上面的页面位于 /lobby。服务器上的 mongoDB 及其架构位于 /mongo
//SERVER
// Mongo.js
/**
* Mongol Database
*/
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://localhost:27017/test');
//var db = mongoose.createConnection('mongodb://nodejitsu_cpiv:es7te3ognihsibnii3a7ekdfu3@ds043927.mongolab.com:43927/nodejitsu_cpiv_nodejitsudb7525674102');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback ()
{
console.log("connected to database tester");
});
/* ====================
// Lobby
// =================== */
var schema = mongoose.Schema,
ObjectId = schema.ObjectId;
var lobbySchema = new schema({
status:Number,
sockets: [{ id:String, team:Number}],
player1:{id:Number},
player2:{id:Number}
});
// Collection
var Lobby = db.model('lobby', lobbySchema);