3

我正在開發一個大型Web應用程序,我正在使用knockout和MVC正確構建它。大型MVC Web應用程序 - 使用Knockout和Razor

目前,我有,我進入了我所有的觀點,即包含有關的基本數據在當前登錄用戶的基本視圖模型

//Example Code 
public class BaseViewModel { 
    public String FullName; 
    public String Email; 

    //A bunch of other similar values 
} 

然後我有一個特定的網站上的每個頁面視圖模型(即配置文件)繼承BaseViewModel類

//profile.cshtml 
public class UserProfileViewModel : BaseViewModel { 
    public String Address; 
    public String PhoneNumber; 

    //Other similar values 
} 

//entity.cshtml 
public class UserEntityViewModel : BaseViewModel { 
    public String EntityValue; 
    public Int32 EntityNumber; 

    //Other similar values 
} 

我一直在使用淘汰賽可觀,這樣我可以創建任何類型的,我有我的MVC模式的對象重新定義在JavaScript我整個的數據模型。然後,我在javascript中定義了幾個視圖模型,它們與我的MVC視圖模型基本相同,以允許加載,創建,編輯和刪除功能。

我發現這很適用於我想從配置文件頁面創建新實體的情況。我可以創建一個viewmodel的新實例,並將其綁定到一個新的jquery對話框,點擊OK按鈕後,我可以在我的knockout viewmodel中調用一個事件來保存或創建實體。

當我想要將數據加載到特定頁面時(即,我想使用我的挖空數據模型填充配置文件頁面),此體系結構不起作用。我遇到了需要確定所處頁面的問題,並將特定的視圖模型綁定到該頁面。我真的不認爲下面的代碼非常優雅。

$(function() { 
    if ($('.tweak-list').length) { 
     var id = $('.tweak-list').attr('data-songid'); 
     var vm = new my.tweaksviewmodel({ songid: id }); 
     ko.applyBindings(vm); 
    } 
}); 

有沒有人有任何建議,我應該如何建築師呢?我認爲最好在javascript中創建BaseViewModel,並使用挖空映射插件http://knockoutjs.com/documentation/plugins-mapping.html自動創建我的各種數據模型。也就是說,它並不能真正解決確定模型已綁定到哪個頁面的問題,以便它可以加載適當的數據。

編輯1

這種架構也有,因爲我需要的視圖模型重新綁定到每一個模態,我不能趁使用模式彈出窗口添加數據的侷限性..

任何人有有任何想法嗎?

回答

4

我會建議建築師以下方式,:

創建具有特異性敲除視圖模型不同的JavaScript模塊,每一頁:

var app = app || {}; 
app.pages = app.pages || {}; 

app.pages.userProfile = (function() { 

    function UserProfileViewModel() { 
     //view model specific code 
    }; 

    function init() { 
     ko.applyBindings(new UserProfileViewModel()); 
    }; 

    return { 
     init: init 
    }; 
}()); 

指定哪些J​​S模塊應在Razor視圖中使用:

@model dynamic 

@{ 
    ViewBag.CurrentPageJsHandler = "app.pages.userProfile"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<p>Page specific content</p> 

添加頁面特定模塊的初始化代碼佈局文件:

<html> 
<body> 
    <div id="content"> 
     @RenderBody() 
    </div>  
    @if (@ViewBag.CurrentPageJsHandler != null) 
    { 
     <script> 
      $(function() { 
       app.currentPage = @ViewBag.CurrentPageJsHandler; 
       app.currentPage.init(); 
      }); 
     </script> 
    }  
</body> 
</html> 

這樣你就可以將所有頁面相關的代碼封裝在不同的模塊中。由於每個JS模塊都有唯一的名稱,因此您可以將它們全部綁定在一起幷包含在佈局中。

+0

我喜歡這個解決方案。我想我可能會使用它的一部分。再次感謝! – mcottingham

相關問題