0

我试图找出一种方法来构建我的应用程序,使 API 交互独立于我的视图和视图模型。

目前,我的 ajax 调用(获取、添加、保存、删除等)和模型(用户模型、消息模型)都在我的视图模型中,但在未来,我们会有一个移动应用程序,它会有点与桌面应用程序不同,因此我想将这些操作保留在一个地方。

我见过人们使用“服务”文件夹,他们有处理加载和存储数据的模型,但还没有看到一个完整的结构,还包括处理新数据和当前数据。

假设我有一个单独的“个人资料页面”外壳,其中包括一个“消息”选项卡和一个“用户详细信息”选项卡。本节需要以下内容:

  • 获取用户详细信息
  • 获取消息
  • 用户模型
  • 消息模型
  • 添加/编辑/删除消息
  • 编辑用户详细信息

我将如何构建这个?单独按组件(带有模型的消息+获取+添加/编辑/删除和带有模型的用户+获取+在单独的文件/文件夹中编辑)或站点区域(一个文件/文件夹中的所有内容)?

希望这是有道理的。谢谢!

4

2 回答 2

1

I'm not experienced in Durandal but have some positive background working with KO. I would recommend you to apply module pattern and incapsulate all your API service methods into the separate class (lets call it Router) also putting it into separate file. And then use methods of the Router class inside viewmodels.

// file with Router class

(function ($, ko, app) {
    app.Router = function () {
        var self = this;

        self.get = function (url, queryString, callBack) {
            $.get(url, data, function(data) {
                callBack(data);
            });
        };

        self.post = function (url, queryString, callBack) {
            $.post(url, data, function(data) {
                callBack(data);
            });
        };

    };
})(jQuery, ko, window.app)

// file with viewmodel

(function ($, ko, app) {
    app.UserModel = function () {
        var self = this;

        //create instance of Router class. 
        //Create it here just for the example. Will be better to create it out of the models to have just one instance. 
        //Or convert Router class to singleton
        var router = new app.Router();

        self.getUserDetails = function() {
            //use proper router method to GET data, providing params
            router.get(properRestServiceUrl, {userID: 1}, self.showUserDetails);
        };

        self.addMessage = function() {
            //use proper router method to POST data, providing params
            router.post(properRestServiceUrl, {userID: 1, message: 'test message'}, self.showConfirmation);
        };

        //callback function
        self.showUserDetails = function(data) {
            alert(data);
        };

        //callback function
        self.showConfirmation = function(data) {
            alert("The message was added successfully!");
        };

    };
})(jQuery, ko, window.app)
于 2013-11-12T15:31:35.413 回答
0

我不知道你在后端使用什么,但如果它是 ASP.NET MVC,我强烈建议你查看 HotTowel 模板。即使它不是 ASP.NET MVC,它仍然是了解如何有效构建应用程序的良好起点。

http://www.asp.net/single-page-application/overview/templates/hottowel-template

于 2013-11-12T15:36:58.877 回答