也许Backbone.js(或其他框架之一)可能是您正在寻找的救援的一部分。
我发现 Backbone 对组织一些继承的意大利面非常有帮助。您的出发点可能是将准备好的大量文档转换为主干视图(或多个)
通过将视图、集合、模型分离到单独的文件中来组织脚本,然后将它们捆绑并压缩到一个文件中,这样浏览器只需要发出一个请求而不是多个请求。
ASP.NET MVC4 可以为你做捆绑,它也可以在 MVC3 上类似地工作
这只是一个简单起点的示例,还有更高级的技术(例如 AMD、require.js)来减少每页的脚本大小,但是通过缓存和 gzip,我发现单个 Everything 脚本包非常适合的案例。
至于您的示例,这是一个可能的主干实现
请记住命名您的代码...
var app = app || {};
$(function ($) {
// depending on your server setup you might be able to just override the url
// and get away with what you want. Otherwise you might look into overriding
// the save/fetch or sync methods of the collection
app.MyListCollection = Backbone.Collection.extend({
url: '/lists/getmylist'
});
app.MyListView = Backbone.View.extend({
//bind the view to the existing element in the HTML.
el: '#MyList',
// your mustache template
template:$('#list-template').html(),
// hook up your event handlers to page components
//(within the context of your el)
events: {
'click #MyButton': 'onMyButtonClick'
},
//called on object creation.
initialize: function () {
//you could create a collection here or pass it into the init function
this.collection = new app.MyListCollection();
//when the collection is changes, call the render method
this.listenTo(this.collection, 'reset', this.render);
},
// render is named by convention, but its where you would "redraw" your view and apply your template
render: function () {
this.$el.html(
Mustache.render(
this.template(this.collection.toJSON())));
return this;
},
//your click handler
onMyButtonClick: function(e){
this.collection.fetch();
}
});
});
使用您的文档准备好启动您需要的任何主干功能,并使用它使用您可能拥有的任何服务器端数据引导您的 JavaScript。
$(function () {
// create an instance of your view
new app.MyListView();
//example bootstrap using razor
app.title = @Model.Title;
});