如何设计jQuery Mobile对话框
在jQuery Mobile中,使用对话框很简单,只需要添加data-role属性为dialog即可,在index.html中添加如下代码:
<!--Invalid Note dialog-->
<div id="invalid-note-dialog" data-role="dialog" data-title="Invalid Note" data-theme="e">
<div data-role="header" data-theme="e">
<h1>Wait!</h1>
</div>
<div data-role="content">Enter a title for this note.</div>
</div>
<div id="invalid-note-dialog" data-role="dialog" data-title="Invalid Note" data-theme="e">
<div data-role="header" data-theme="e">
<h1>Wait!</h1>
</div>
<div data-role="content">Enter a title for this note.</div>
</div>
接下来,我们还要在控制层中添加对话框的标识,
var invalidNoteDlgSel = "#invalid-note-dialog";
我们将修改onSaveNoteButtonTapped事件的代码如下:
var onSaveNoteButtonTapped = function () {
// 校验记事
var titleEditor = $(noteTitleEditorSel);
var narrativeEditor = $(noteNarrativeEditorSel);
var tempNote = dataContext.createBlankNote();
tempNote.title = titleEditor.val();
tempNote.narrative = narrativeEditor.val();
if (tempNote.isValid()) {
if (null !== currentNote) {
currentNote.title = tempNote.title;
currentNote.narrative = tempNote.narrative;
} else {
currentNote = tempNote;
}
dataContext.saveNote(currentNote);
returnToNotesListPage();
} else {
$.mobile.changePage(invalidNoteDlgSel, defaultDlgTrsn);
}
};
我们将修改onSaveNoteButtonTapped事件的代码如下:
var onSaveNoteButtonTapped = function () {
// 校验记事
var titleEditor = $(noteTitleEditorSel);
var narrativeEditor = $(noteNarrativeEditorSel);
var tempNote = dataContext.createBlankNote();
tempNote.title = titleEditor.val();
tempNote.narrative = narrativeEditor.val();
if (tempNote.isValid()) {
if (null !== currentNote) {
currentNote.title = tempNote.title;
currentNote.narrative = tempNote.narrative;
} else {
currentNote = tempNote;
}
dataContext.saveNote(currentNote);
returnToNotesListPage();
} else {
$.mobile.changePage(invalidNoteDlgSel, defaultDlgTrsn);
}
};
这里,请注意$.mobile.changePage(invalidNoteDlgSel, defaultDlgTrsn);
这句。在这里,我们使用了 $mobile.changePage方法,这个方法能动态地触发页面改变。这个方法有两个参数,第一个参数是要出现的页面的id(这里就是对话框的id),而第二个参数则是页面切换的效果,这里使用的过渡切换效果如下定义:
var defaultDlgTrsn = { transition: "slideup" };
mobileinit事件的放置位置
在上一讲中,我们在index.html中编写了mobileinit事件的代码,但这个习惯不是很好,我们不希望在html页中出现跟逻辑相关的代码,因此我们重构一下,将mobileinit事件的代码放到Controller.js这个文件中进行处理,代码如下:
Notes.controller = (function ($, dataContext, document) {
//省略了详细的contoller代码,具体见附件
} (jQuery, Notes.dataContext, document));
$(document).bind("mobileinit", function () {
Notes.controller.init();
});
//省略了详细的contoller代码,具体见附件
} (jQuery, Notes.dataContext, document));
$(document).bind("mobileinit", function () {
Notes.controller.init();
});
现在,index.html代码中,则只是引用了相关的JS文件了,不会再象上一讲中,在index.html中混杂了js代码。