Mongoose/Express가 포함 된 Backbone.js.Backbone.js Node.js 서버에서 모델에 액세스
서버에서 db 및 모델과 통신하는 방법을 이해하는 데 가장 힘든 시간을 보내고 있습니다. 솔직히 나는 모델과 서버의 관계를 이해하지 못한다. 클라이언트의 모델이 서버의 모델과 동기화됩니까? 서버에 모델이 있습니까? 현재 MongoDB에는 데이터가 채워져 있으며, 시도하려는 모든 임자는 fetch()를 작동시키는 것입니다. 어떤 도움이 될 것입니다. 백본이 이미이 모든 작업을 수행 할 때 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:[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);