0

对 JavaScript 来说相当新,所以这可能是一个无聊的问题。

目前,对于我的项目,我将 NodeJS 用于服务器,将 Backbone 用于客户端。客户端将向服务器发送请求,服务器将发送服务器中的文件列表,我的目的是简单地返回文件列表,当用户单击文件时,它将向服务器发送另一个请求以加载文件.

目前在客户端级别,我的模型和集合定义如下:

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();
});

我的服务器代码:

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?
}

由于加载目录中的所有文件并将其发送回客户端是没有意义的,所以我所做的是我在服务器中创建模型并填充modifiedDatepath同时离开contentnull. content但现在的问题是,当用户点击文件时,我该如何填写?我不确定如何从 Backbone View 或控制器手动发送 HTTP 请求。或者有没有更好的方法来做到这一点?我能想到的一种方法是创建另一个只保留的模型,modifiedDatepath对我来说这看起来非常冗长和重复。

4

2 回答 2

2

鉴于您在客户端拥有的东西,您可能不再需要任何东西。

app.MyFiles = new MyFileList();

app.MyFiles.fetch().done(function() {
   // your collection is fetched but each model's content is empty.
   // now, I assume at this point you will show them in some view/views.
});

现在,当单击其中之一时,您可以获取内容。

var model = app.MyFiles.get(id);
model.fetch().done(function() {
    // now the model's content attribute will be set
});

这可能只使用您展示的代码。因为默认情况下,模型用于获取的 url 是通过将模型的 id 附加到其集合 url 的末尾来创建的。

所以从你的服务器,你从'/api/files'返回一个json数组:[{id:1, path:'foo'}, {id:2, path:'bar'}]

然后从'/api/files/1':{id:1, path:'foo', content:'whatever'}

于 2013-03-29T06:41:41.293 回答
1

当用户单击文件时,您可以在模型上调用主干的fetch方法。然后,您的模型将填充来自服务器的数据。

请注意,要使其正常工作,您应该首先从服务器返回集合,其中模型至少具有 id。fetch通话后将填写所有其他字段。此外,如果模型 url与标准(即)不同,您应该覆盖它collection/id

于 2013-03-29T06:41:30.477 回答