MVVM是一种架构思想,是一种解决问题的方式,对于一个项目,一个功能模块,你可以选择使用MVVM的架构来实现,而knockoutjs只是实现MVVM的一种工具,它是在前端实现的,这一点,我们必须的清楚.

思想

下面说一下这讲的重点,前台和后台的分工问题,占占认为,前台只负责页面及页面CSS及实现效果的JS,而后台的工作包括业务的处理,数据的持久化,前台数据的绑定(knockoutjs)等等.

实践

下面是前台HTML代码

<table border="1">
    <tr>
        <th>QuestionInfoID
        </th>
        <th>用户</th>
        <th>类型</th>
        <th>知识点</th>
        <th>难度</th>
        <th>日期</th>
        <th>年级</th>
        <th>学科</th>
        <th>图像</th>
    </tr>
    <tbody data-bind="foreach:model">
        <tr>
            <td data-bind="text:QuestionInfoID"></td>
            <td>
                <span data-bind="if:Partner_Info"><span data-bind="text:Partner_Info.AccountName"></span></span>
                <span data-bind="if:User_Info"><span data-bind="text:User_Info.RealName"></span></span>
            </td>
            <td data-bind="text:OwnerType"></td>
            <td data-bind="text:Knowledge"></td>
            <td data-bind="text:Difficulty"></td>
            <td data-bind="text:AddTime"></td>
            <td data-bind="foreach:Question_Point_R"><span data-bind="text:Point_Info.Grade"></span></td>
            <td data-bind="foreach:Question_Point_R"><span data-bind="text:Point_Info.Subject"></span></td>
            <td>
                <img width="21" height="21" src="1.jpg" onerror="errorImg(this)" /></td>
        </tr>
    </tbody>

</table>

下面是后台的knockoutjs代码

@Html.Pager(Model)//C#数据分页
<script type="text/ecmascript">
    //图像加载出错时的处理
    function errorImg(img) {
        img.src = "http://www.baidu.com/img/bdlogo.gif";
        img.onerror = null;
    }

    var model = ko.observableArray(@Html.Raw(Json.Encode(Model)));//从后台得到数据集合,并转化为json对象
    ko.applyBindings(model);
</script>

运行截图

MVVM架构~前台后台分离的思想与实践

说明

在这个例子中,我们使用了knockoutjs里的if,foreach等关键字,if可以判断一个对象是否为空,而foreach可以把集合对象遍历出来.

本文转自博客园张占岭(仓储大叔)的博客,原文链接:MVVM架构~前台后台分离的思想与实践,如需转载请自行联系原博主。

相关文章:

  • 2022-12-23
  • 2021-10-08
  • 2021-11-01
  • 2021-08-27
  • 2021-12-22
  • 2022-12-23
  • 2021-04-21
  • 2021-07-08
猜你喜欢
  • 2022-12-23
  • 2021-11-02
  • 2021-11-23
  • 2021-06-03
  • 2021-05-12
相关资源
相似解决方案