5

我希望制作一个 Durandal 自定义对话框,在现有的可组合视图模型周围添加一个带有标题和页脚的窗口框架。

我制作了一个 customModal.html 模板

<div class="messageBox">
    <div class="modal-header">
        <h3 data-bind="text: title"></h3>
    </div>
    <div class="modal-body">
        <!--ko compose: { model: model, template: view }-->
        <!--/ko-->
    </div>
    <div class="modal-footer" data-bind="foreach: options">
        <button class="btn" data-bind="click: function () { $parent.selectOption($data); }, text: $data, css: { 'btn-primary': $index() == 0, autofocus: $index() == 0 }"></button>
    </div>
</div>

如您所见,我希望在 customModal 模板的主体中组成一个视图模型。这样一来,传入的视图模型就不会绑定到模态显示,而是可以轻松使用。

我制作了一个这样的 customModal.js 模型:

define(['plugins/dialog'], function (dialog) {
    var CustomModal = function (title, model, view, options) {
        this.title = title;
        this.model = model;
        this.view = view;
        this.options = options;
    };

    CustomModal.prototype.selectOption = function (dialogResult) {
        dialog.close(this, dialogResult);
    };

    return CustomModal;
});

但是当我尝试使用它时,组合绑定搜索模板“.html”并失败。

我在这里错过了什么吗?这真的是最好的方法吗?

谢谢。

4

1 回答 1

7

我创建了一个简化的示例,您可以将其用作起点。它由一个索引视图/虚拟机组成,可以选择在 customModal 中打开现有视图/虚拟机。现有视图模型在关闭时返回,以便可以访问。

index.js

define(function(require){
    "use strict";

    var app = require('durandal/app'),
        CustomDialog = require('./customModal'),
        Existing = require('./existingView'),
        ctor;

    ctor = function(){
        this.dialog;
    };

    ctor.prototype.showCustomModal = function(){
        this.dialog = new CustomDialog('My title', new Existing());

        this.dialog.show().then(function(response){
            app.showMessage('Model title "' + response.title + '".');
        });
    };

    return ctor;

});

索引.html

<div>
    <h3>Durandal 2.0 custom dialog</h3>
    <a href="#" data-bind="click: $data.showCustomModal">click here </a> to open an existing view model in a custom
    dialog.
</div>

customModal.js

define(['plugins/dialog'], function (dialog) {
    var CustomModal = function (title, model) {
        this.title = title;
        this.model = model;
    };

    CustomModal.prototype.ok = function() {
         dialog.close(this, this.model);
     };

    CustomModal.prototype.show = function(){
       return dialog.show(this);
    };

    return CustomModal;
});

customModal.html

<div class="messageBox">
    <div class="modal-header">
        <h3 data-bind="text: title"></h3>
    </div>
    <div class="modal-body">
        <!--ko compose: $data.model-->
        <!--/ko-->
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" data-bind="click: ok">Ok</button>
    </div>
</div>

现有的View.js

define(function () {

    var ctor = function () {
        this.title = 'I\'m an existing view';
    };

    return ctor;
});

现有的View.html

<p data-bind="text: title"></p>

现场版本可在http://dfiddle.github.io/dFiddle-2.0/#so/21821997 获得。随意分叉。

于 2014-02-17T13:42:46.337 回答