纯粹与UI相关的javascript在Durandal视图中的位置在哪里?
作者:互联网
我正在玩一个基于Durandal的SPA,并遵循他们的’views’和’viewmodels’的惯例,基本功能正常.即使用somepage.html& somepage.js.
但是,当添加更多交互式UI元素(例如可折叠的手风琴或信息弹出窗口)时,处理这些事件的javascript应该放在哪里?将它放在somepage.js viewmodel文件中并不是“闻”的权利 – 这是…视图模型!
从最佳实践角度来看,在somepage.html文件中有一个脚本块会更好吗?例如.
<section>
<!- html markup and data-binding goes here>
</section>
<script type="text/javascript">
<!-- UI-only Javascript goes here>
</script>
或者,还有更好的方法?
解决方法:
我也一直在努力解决这个问题,我同意在viewModel中添加与视图相关的东西.我需要做的就是attach a delegated event handler的原因 – 这不能像使用自定义绑定或小部件那样完成.
我和同事提出的最佳解决方案是从viewModel传播viewAttached事件,并在“视图文件”中侦听事件.
使用名为“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;
});
希望有所帮助.
标签:durandal,javascript,single-page-application 来源: https://codeday.me/bug/20190729/1567545.html