帶Mongoose/Express的Backbone.js。Backbone.js Node.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);
上面的頁面住在/大堂。服務器上的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:[email protected]: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);