【发布时间】:2010-11-11 02:25:36
【问题描述】:
注意:这是一个冗长的问题,需要很好地理解 MVVM“设计模式”、JSON 和 jQuery....
所以我有一个理论/主张,即 DHTML 中的 MVVM 可能和可行,并且想知道您是否同意/不同意我的观点以及原因。在 DHTML 中实现 MVVM 围绕使用 ajax 调用返回 JSON 的服务器实体,然后通过 javascript 使用 html 操作来控制 html。
所以把它分解。假设我正在构建一个在数据库中搜索 People 的搜索页面.....
视图看起来像这样:
<body viewmodel="SearchViewModel">
Search:<br />
<input type="text" bindto="SearchString" /><br />
<input type="button" value="Search" command="Search" />
<br />
<table bindto="SearchResults">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>${FirstName}</td>
<td>${LastName}</td>
</tr>
</tbody>
</table>
</body>
在我的 html 元素上使用一些非标准属性,我已经声明性地定义了一个 View 以及它将如何与我的 ViewModel 交互。我在 javascript 中创建了一个 MVVM 解析器,它解释非标准属性并将 View 与代表 ViewModel 的 JSON 对象相关联。
ViewModel 将是一个 JSON 对象:
//View Model SearchViewModel would be assocaited with View because of <body viewmodel="SearchViewModel">
var SearchViewModel = {
//SearchString variable has a TwoWay binding
//to <input type="text" bindto="SearchString" /><
//if a user types into the text box, the SearchString property will "auto-magically" be updated
//because of the two way binding and how the element was interpreted via my MVVM parser
SearchString: '',
//SearchResults has a OneWay binding to <table bindto="SearchResults">
SearchResults: new Array(),
//Search function will get "auto-magically" get called because of
//the command binding to <input type="button" command="Search" />
Search: function() {
//using jquery to call into the server asynchronously
//when the server call is completed, the PopulateSearchResults method will be called
$.getJSON("www.example.com/SearchForPerson",
{ searchString: SearchViewModel.SearchString },
SearchViewModel.PopulateSearchResults);
}
PopulateSearchResults: function(data) {
//set the JSON array
SearchViewModel.SearchResults = data;
//simulate INotifyPropertyChanged using the MVVM parser
mvvmParser.notifyPropertyChanged("SearchResults");
}
}
Model 可以是任何返回 JSON 的服务器端资产...在这个例子中,我使用了 asp MVC 作为一个 restful 外观:
public JsonResult SearchForPerson(string searchString)
{
PersonDataContext personDataContext = new PersonDataContext(); //linq to sql.....
//search for person
List<Person> results =
personDataContext.Persons
.Where(p => p.FirstName.Contains(searchString)
|| p.LastName.Contains(searchString))
.ToList();
return Json(results);
}
那么,问题又来了:
MVVM 在 DHTML RIA 应用程序(没有 Silverlight/WPF)中是否可行/可行,还是我失去了理智?
这个“MVVM 框架”是个好主意吗?
概念证明:kaboom.codeplex.com。
【问题讨论】:
标签: javascript asp.net-mvc json mvvm dhtml