如何在Mithril.js中覆盖弹出视图

How Do I Overlay a Popup View in Mithril.js?

本文关键字:覆盖 视图 js Mithril      更新时间:2023-09-26

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

我现在正在尝试实现删除和合并,这两种操作在执行之前都需要弹出确认,这就是我遇到的问题。我很清楚在桌面GUI环境中我会做什么,所以障碍可能是我对浏览器前端的理解不足,而不是对Mithril本身的理解

理想情况下,我想创建一个独立的、可重复使用的"弹出窗口"组件来表示弹出窗口,但我不知道我应该如何使用Mithril在JS中做到这一点,特别是,但不仅仅是,如何使Mithril将一个视图覆盖在另一个视图上。

从概要到具体的代码片段,任何帮助都将不胜感激。

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

//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),也可以使用带有自己的CSS 的样式.modal

/*really contrived example to get you started*/
.modal {
  background:#fff;
  border:1px solid #eee;
  position:fixed;
  top:10px;
  left:100px;
  width:600px;
}

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

因此,基本上,我依赖Mithril自上而下的重新渲染方法,根据当前应用程序状态有条件地构建视图——它运行得非常好,对我来说非常明智

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

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

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

在视图中,如果有一个确认排队,则创建一个确认视图div,否则创建一个空占位符(如果容器元素在渲染之间不出现和消失,则Mithrils差异效果最佳):

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来定位受影响的记录,它可以抵御模型中的干预更改,比如对列表进行排序。