I am relatively new to JavaScript, so please bear with me as I ask this question.
Currently, for my project, I am using NodeJS for the server and Backbone for the client. The idea is that the client will send a request to the server, which will then respond by sending a list of files stored on the server. My goal is to simply display this list of files to the user and allow them to click on a file to load its content by sending another request to the server.
In the client-side code, my model and collection are defined as follows:
app.MyFile = Backbone.Model.extend({
defaults: {
modifiedDate: new Date(),
path: '',
content: '' // content of the file
}
});
var MyFileList = Backbone.Collection.extend({
model: app.MyFile,
url: '/api/files'
});
// create global collection of files
app.MyFiles = new MyFileList();
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();
});
And here is part of the server-side code:
var application_root = __dirname,
express = require("express"),
...
app.get('/api/files', function(req, res) {
...
// return file list
}
app.get('/api/files/:id', function(req, res) {
...
// return file content?
}
Since it would be inefficient to load and send back all files from the directory at once, I decided to create the model on the server side and populate modifiedDate
and path
, leaving content
as null. However, the challenge now is how to populate the content
when a user clicks on a file. I am unsure about how to manually send an HTTP request from a Backbone View or controller. Are there any better approaches to tackle this issue? One solution that comes to mind is creating another model that only stores modifiedDate
and path
, but this seems verbose and repetitive to me.