我一直在爲此而苦苦掙扎,我同意將視圖相關的東西放入viewModel中。我需要做的是你要說的是attach a delegated event handler - 這不能像使用自定義綁定或小部件那樣完成。
一位同事和我想出的最佳解決方案是從viewModel傳播viewAttached
事件,並在「視圖文件」中偵聽事件。
使用一個名爲 「真棒」 作爲一個例子來看,我們正在使用的命名約定是這樣的:
- 視圖模型 - 的ViewModels/awesome.js
- 查看 - 視圖/ awesome.html
- 查看文件 - 視圖/ 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;
});
希望有所幫助。
HTML的JavaScript應該由**綁定**或**小部件**處理。如果你想要一個淘汰賽的手風琴,谷歌它。在某些情況下,彈出窗口可以由視圖模型處理。 – Tyrsius