我正在嘗試開發一個簡單的文件瀏覽器,它使用客戶端的Backbone和服務器的Node.js。此刻我很卡如何當涉及到子文件夾模型中的骨幹集合+使用Node.js的restful服務器設計
客戶端代碼設計的模型看起來像
app.MyFile = Backbone.Model.extend({
defaults: {
path: '', // id of the model will be the path + filename
content: '', // content of the file
isDir: false // if file is a directory
}
});
var MyFileList = Backbone.Collection.extend({
model: app.MyFile,
url: '/api/files'
});
// create global collection of files
app.MyFiles = new MyFileList();
// displays file name
var MyFileItemView = Backbone.View.extend({
events: {
'click .clickable': 'view'
},
...
view: function (source) {
if (this.model.toJSON().isDir) {
this.model.fetch();
// XXX what to do here
_.each(this.model.get('content'), function (obj) {
console.log(obj.toJSON()); // error - no toJSON method
});
} else {
// calls another view that calls the model.fetch
// to display the content (no issue here)
}
},
});
var MyFilesListView = Backbone.View.extend({
initialize: function() {
// XXX Not sure if I should listen on MyFiles collection...
app.MyFiles.on('reset', this.render, this);
},
render: function() {
app.MyFiles.each(function (file) {
new MyFileItemView({model:file});
}, this);
});
app.AppView = Backbone.View.extend({
initialize: function() {
// fetch all files
app.MyFileList.fetch();
}
});
// app.js (point of entry)
$(function() {
// Kick things off by creating the **App**.
new app.AppView();
});
我的服務器代碼:
var express = require("express"),
...
app.get('/api/files', function(req, res) {
...
// return file list (including folder - no issue here)
}
app.get('/api/files/:id', function(req, res) {
var fileModel = createFileModel(req.params.id); // create file model
if (!fileModel.isDir) {
// if file is not directory, then simply read the content and return
// it back to the client -- no issue
...
} else {
var files = [];
// read the directory to find all the files and push it to
// files array
...
fileModel.content = files;
res.send(fileModel);
}
}
目前我我不確定什麼是正確的做法。我的問題:
- 如何表示模型對象本身。如果
isDir===true
?我應該將內容設置爲MyFile的集合嗎?如果是這樣的話,我該怎麼做?在模型的內容上調用toJSON()
會拋出異常,因爲toJSON
未定義 - 還應該在
MyFilesListView
上偵聽全局集合嗎?現在我需要處理子文件夾,這看起來不正確。 - 或者我應該在嘗試查看子文件夾時覆蓋全局集合嗎?
- 我的服務器代碼實現是否正確?我現在遇到的問題是,當我將內容放入數組並將fileModel發送回客戶端時,文件列表未反映在模型本身中 - 可能我必須覆蓋
parse
?
我看了一些帖子這裏
- Nested models of the same 'class' in the Backbone.js framework?
- Backbone: fetch collection from server
- How to build a Collection/Model from nested JSON with Backbone.js
但我仍然不知道如何使用它... JavaScript是令人困惑: (