我希望创建一个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模板的主体内构建一个viewmodel。这样传入的视图模型不依赖于模态显示,但可以轻松使用。
我已经制作了这样的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;
});
但是当我尝试使用它时,compose绑定会搜索模板'.html'并失败。
我在这里遗漏了什么吗?这真的是最好的方法吗?
感谢。
答案 0 :(得分:7)
我创建了一个可以用作起点的简化示例。它由索引视图/ vm组成,可选择在customModal中打开现有视图/ vm。现有的视图模型在关闭时返回,以便可以访问。
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;
});
<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>
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;
});
<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>
define(function () {
var ctor = function () {
this.title = 'I\'m an existing view';
};
return ctor;
});
<p data-bind="text: title"></p>
http://dfiddle.github.io/dFiddle-2.0/#so/21821997提供实时版本。随意分叉。