我也一直在为此苦苦挣扎,并且我同意将与视图相关的东西放入 viewModel 的气味中。我需要做你所说的事情的原因是附加一个委托的事件处理程序- 这不能像建议的那样使用自定义绑定或小部件来完成。
我和同事想出的最佳解决方案是viewAttached
从 viewModel 传播事件,并在“视图文件”中侦听事件。
以名为“awesome”的视图为例,我们使用如下命名约定:
- 视图模型- viewmodels/awesome.js
- 查看-views/awesome.html
- 查看文件-views/awesome.html.js
这是我们正在做的事情的简化版本。
viewmodels/awesome.js:
define([
"durandal/app",
"durandal/system",
// require the view file; note we don't need a reference to it,
// we just need to make sure it's loaded
"views/myView.html"
],
function (app, sys) {
var viewModel = {
// whatever
};
viewModel.viewAttached = function(view) {
// Create a namespace for the event
var eventNamespace = sys.getModuleId(viewModel)
.replace("viewmodels", "")
.replace("/", ".");
// This will evaluate to 'awesome.viewAttached'
var eventName = eventNamespace + ".viewAttached";
// Trigger the event and pass the viewModel and the view
app.trigger(eventName, viewModel, view);
};
return viewModel;
});
意见/awesome.html.js:
define([
"durandal/app"
],
function (app) {
var module = {
viewAttached: function(viewModel, view) {
// do your thing! make sure any selectors you use use the view as the parent selector,
// because you're not guaranteed that your view is in the DOM (only that it's attached
// to its parent).
var $submit = $("#submit", view);
}
};
// wire-up
app.on("awesome.viewAttached", module.viewAttached);
// export
return module;
});
希望有帮助。