5

作为深入学习基本 JS 编程的实践练习(在最新的浏览器上),我正在构建一个 SPA 来维护客户记录。我使用的唯一外部库是 Mithril.js MVC。到目前为止,我已经从我的数据库中获得了一个包含实时数据的表格视图,其中包括每条记录的编辑、合并和删除按钮。编辑完成并且运行良好,使用内联“表单”并保存/取消该作品。

我现在正在尝试实现删除和合并,这两者都需要在被操作之前弹出确认,这就是我卡住的地方。我确切地知道我会在桌面 GUI 环境中做什么,所以障碍可能是我对浏览器前端的了解比对 Mithril 本身的了解更多。

理想情况下,我想创建一个独立的、可重复使用的“弹出”组件来表示弹出窗口,但我看不出我应该如何使用 Mithril 在 JS 中执行此操作,特别是但不仅限于如何制作秘银将一个视图覆盖在另一个视图之上。

从粗略的大纲到特定的代码片段,任何帮助都将不胜感激。

4

2 回答 2

5

您可能想使用视图模型标志来控制模式弹出窗口的可见性。

//modal module
var modal = {}
modal.visible = m.prop(false)
modal.view = function(body) {
  return modal.visible() ? m(".modal", body()) : ""
}

//in your other view
var myOtherView = function() {
  //this button sets the flag to true
  m("button[type=button]", {onclick: modal.visible.bind(this, true)}, "Show modal"),

  //include the modal anywhere it makes sense to
  //its visibility is taken care by the modal itself
  //positioning is controlled via CSS
  modal.view(function() {
    return m("p, "modal content goes here")
  })
}

要制作模态对话框,您可以使用来自众多 CSS 框架之一的样式(例如 Bootstrap),也可以.modal使用您自己的 CSS 样式

/*really contrived example to get you started*/
.modal {
  background:#fff;
  border:1px solid #eee;
  position:fixed;
  top:10px;
  left:100px;
  width:600px;
}
于 2014-09-19T01:56:19.743 回答
4

我不知道我是否只是不太了解 MVC,但我只是设置了一个包含弹出窗口细节的视图模型对象,然后在生成视图时(如果当前已设置)我填充包含弹出窗口的 div。CSS 控制外观和定位。

所以基本上我依靠 Mithril 的自上而下的重新渲染方法来有条件地基于当前应用程序状态构建视图——它工作得非常好,并且对我来说非常明智。

我实际上使用了一个弹出确认对象列表,因此多个确认可以排队。

在控制器中,创建一个确认队列:

function Controller() {
    ...
    this.confirmation                   =[];
    ...
    }

在视图中,div如果有确认队列,则创建一个确认视图,否则创建一个空占位符(如果容器元素在渲染之间没有出现和消失,秘银差分效果最好):

function crtView(ctl) {
    ...
    return m("div", [
        ...
        crtConfirmationView(ctl),
        ...
        ]);
    }

function crtConfirmationView(ctl) {
    var cfm=ctl.confirmation[0];

    return m("div#popup-confirm",(cfm ? muiConfirm.crtView(ctl,cfm.title,cfm.body,cfm.buttons) : null));
    }

然后,每当需要确认时,只需将确认对象推入队列,让 Mithril 的绘图系统运行并重建视图。

function deleteRecord(ctl,evt,row,idx,rcd) {
    var cfm={
        title   : m("span","Delete Customer: "+rcd.ContactName),
        body    : [
            m("p","Do you really want to delete customer "+rcd.CustomerId+" ("+rcd.ContactName+") and all associated appointments and addresses?"),
            m("p.warning", "This action cannot be undone. If this is a duplicate customer, it should be merged with the other record."),
            ],
        buttons : deleteButtons,
        proceed : "delete",
        index   : idx,
        record  : rcd,
        };

    ctl.confirmation.push(cfm);
    }

确认对象包含confirm帮助函数crtView创建确认视图所需的任何属性,然后在用户单击按钮(或按 ENTER 或 ESCAPE 等)时执行操作——只是您抽象为共享可重用组件的标准 UI 内容。


注意:以防万一有人对数组索引有疑问,我已经不再使用数组索引来识别数据模型中的记录(当删除完成时,应该删除数组元素)。相反,我使用数据库 ID 定位受影响的记录,该 ID 可以抵御模型中的干预更改,例如对列表进行排序。

于 2014-10-11T20:42:10.643 回答