我正在尝试使用yahoo ui历史库。我没有看到一个很好的方法来避免用Y.use包装我的所有函数内容,以便我可以访问历史对象。我尝试在use()命令之外全局声明它,但这似乎不起作用。如果你查看我的showDashboard()和showReport1()方法,你可以看到我正在包装内容,这对于使用历史记录的每个函数来说都是多余的。有一个更好的方法吗?
我见过的所有雅虎示例都没有完整的功能,并将整个示例保留在单一使用方法中。
<div>
<a href="#" onclick="showDashboard(); return false;">Dashboard</a> |
<a href="#" onclick="showReport1(); return false;">Report 1</a>
</div>
<script type="text/javascript">
// Global reference to Yahoo UI object
var Y = YUI();
function showDashboard() {
Y.use('*', function (Y) {
var history = new Y.HistoryHash();
history.addValue("report", "dashboard");
});
}
function showReport1() {
Y.use('*', function (Y) {
var history = new Y.HistoryHash();
history.addValue('report', "report1");
//var x = { 'report': 'report1', 'date': '11/12/2012' };
//history.addValue("report", x);
});
}
Y.use('history', 'tabview', function (Y) {
var history = new Y.HistoryHash();
var tabview = new Y.TabView({ srcNode: '#demo' });
// Render the TabView widget to turn the static markup into an
// interactive TabView.
tabview.render();
// Set the selected report to the bookmarked history state, or to
// the first report if there's no bookmarked state.
tabview.selectChild(history.get('report') || 0);
// Store a new history state when the user selects a report.
tabview.after('selectionChange', function (e) {
// If the new tab index is greater than 0, set the "tab"
// state value to the index. Otherwise, remove the "tab"
// state value by setting it to null (this reverts to the
// default state of selecting the first tab).
history.addValue('report', e.newVal.get('index') || 0);
});
// Listen for history changes from back/forward navigation or
// URL changes, and update the report selection when necessary.
Y.on('history:change', function (e) {
// Ignore changes we make ourselves, since we don't need
// to update the selection state for those. We're only
// interested in outside changes, such as the ones generated
// when the user clicks the browser's back or forward buttons.
if (e.src === Y.HistoryHash.SRC_HASH) {
if (e.changed.report) {
// The new state contains a different report selection, so
// change the selected report.
tabview.selectChild(e.changed.report.newVal);
} else if (e.removed.report) {
// The report selection was removed in the new state, so
// select the first report by default.
tabview.selectChild(0);
}
}
if (e.changed.report) {
alert("New value: " + e.changed.report.newVal);
alert("Old value: " + e.changed.report.prevVal);
}
});
});
</script>
</form>
</body>
</html>
答案 0 :(得分:3)
不使用单击上的普通函数,而是使用YUI附加处理程序。 如果您可以更改HTML代码 - 将ID或类添加到链接,例如
<a id="btnShowDashboard" href="#">Dashboard</a>
然后在你的use()中添加点击处理程序到按钮
Y.use('history', 'tabview', 'node', 'event', function (Y) {
var bntShowDashboard = Y.one('#btnShowDashboard');
if (bntShowDashboard) {
bntShowDashboard.on('click', function(e) {
e.preventDefault();
var history = new Y.HistoryHash();
history.addValue("report", "dashboard");
});
}
...
})
这样你就可以确保在执行“历史”的那一刻加载。 但是有一个缺点 - 在加载YUI模块之前,如果你点击链接就不会发生任何事情。