2013-03-29 208 views
0

JavaScript的相当新,所以它可能是一个noobish问题。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,同时将content更改为null。但现在的问题是,如何在用户点击文件时填写content?我不确定如何手动发送来自Backbone View或控制器的HTTP请求。或者有没有更好的方法来做到这一点?我能想到的一种方式是创建另一个只保留modifiedDatepath的模型,但对我来说这看起来非常冗长和重复。

回答

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

这可能不会比你显示的代码更多的代码。由于默认情况下通过将模型的ID附加到其集合的url的末尾来创建模型用来提取的url。

所以从你的服务器,你回来从'/ API /文件的JSON数组:[{id:1, path:'foo'}, {id:2, path:'bar'}]

然后从 '/ API /文件/ 1':{id:1, path:'foo', content:'whatever'}

+0

真棒。我不知道你可以从模型中调用fetch()。阅读api时一定错过了它。谢谢! – GantengX

1

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

请注意,为了这个工作,你应该首先从服务器返回集合,其中模型至少有id。在fetch电话后,其他所有字段将被填写。此外,如果它不同于标准(它是collection/id),则应该覆盖model url