0

这些天来,我发现自己将很多代码放在我觉得$(document).ready()不干净的地方。例如,如果我正在创建将通过 ajax 查询我的数据库并将其返回并将其附加到我的列表的内容,我会执行以下操作:

$(function(){
   //Initialize my DOM elements
   $MyList = $("#MyList"),
   $MyButton = $("#MyButton");

   //Add my Click event
   $MyButton.click(function(){
      $.ajax({
         type: 'POST',
         url: "/lists/getmylist",
         contentType: "application/json",
         success: function(results){
            //Parse my results and append them using my favorite templating helper
            var jsonResults = $.parseJSON(result);
            $MyList.mustache("my-template", jsonResults);
         }
      });
   })
});

现在我知道这是一个小例子,但是当我有多个点击事件、ajax 请求等时它开始变得非常大和混乱。这一切最终都在我的文档中准备好了。我知道我可以将我所有的 ajax 请求放在一个外部 javascript 文件中以帮助使其更干净,但是这种架构通常可以吗?看起来它真的很乱。我见过其他人使用插件架构或初始化函数。我通常在我所有页面的底部准备好这个文档,然后放入使我的页面正常工作所需的任何内容。这是构建我的js的好方法吗?

4

2 回答 2

4

我认为添加一些模型对象和一般的面向对象编程原则可能会在这里大有帮助。如果您将数据获取和存储中断到模型类中,它应该会有很大帮助。

这里有一些链接可以让你开始思考 OO 与 Javascript。

编写面向对象的 JavaScript

Javascript 设计模式

Javascript:原型继承 Javascript:原型继承 2

另一件可能会有所帮助的事情是将 Javascript 分解为多个文件。一个用于全局脚本,可能通过附加到所有页面的标题和需要它的每个页面的脚本包含在内。

于 2013-03-15T00:07:45.253 回答
1

也许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;
});
于 2013-03-15T14:42:55.273 回答