【问题标题】:Reload the page using sammy.js使用 sammy.js 重新加载页面
【发布时间】:2015-04-16 04:42:49
【问题描述】:

我在 asp.net mvc 中将 sammy.js 用于单页应用程序。
一切都很好,但我面临一个问题,就是我无法重新加载页面。
例如,当我在仪表板中时,我的 URL 是

http://localhost:1834/#/Home/Index?lblbreadcum=Dashboard

layout.cshtml

 <script>
    $(function () {

        var routing = new Routing('@Url.Content("~/")', '#page', 'welcome');

        routing.init();

    });
</script>

routing.js

var Routing = function (appRoot, contentSelector, defaultRoute) {

function getUrlFromHash(hash) {

    var url = hash.replace('#/', '');
    if (url === appRoot)
        url = defaultRoute;

    return url;
}

return {

    init: function () {
        Sammy(contentSelector, function () {


            this.get(/\#\/(.*)/, function (context) {
                var url = getUrlFromHash(context.path);

                context.load(url).swap();

            });

        }).run('#/');
    }
};
}

我想通过单击仪表板菜单/链接重新加载页面。但是点击事件没有触发,因为链接没有改变。但是,如果我想转到另一页,那很好。请帮帮我。谢谢。

【问题讨论】:

  • 您好,您要完全刷新页面吗?在这种情况下,你不能在说 /# 时这样做,因为它指向一个锚点……我理解正确吗?
  • 我想刷新唯一的部分视图而不是整个页面。

标签: javascript jquery asp.net asp.net-mvc sammy.js


【解决方案1】:

我认为您必须再次附加相同的部分。你不能“更新”那个意思的部分。 正如您在帖子中所说,当您单击另一个链接然后再次返回时,它会起作用。

这就是你必须要做的。再次附加相同的页面/部分,通过这样做你清除所有变量并重新创建它们,通过模拟刷新。

编辑:添加示例 请注意,我没有直接复制您的代码,但我想您会理解 :) 在我的示例中,我没有使用哈希 (#)。

var app = Sammy(function () {

        this.get('/', function (context) {
             // context is equalient to data.app in the custom bind example
             // currentComponent('home'); I use components in my code but you should be able to swith to your implementation
            var url = getUrlFromHash(context.path);
            context.load(url).swap();
        });

        this.bind('mycustom-trigger', function (e, data) {
            this.redirect('/'); // force redirect
        });

        this.get('/about', function (evt) {
            // currentComponent('about'); I use components in my code but you should be able to swith to your implementation
            var url = getUrlFromHash(context.path);
            context.load(url).swap();
        });

    }).run();

    // I did an easy example trigger here but I think you will need a trigger on your link-element. Mayby with a conditional check wheter or not to trigger the manually binding or not
    $('.navbar-collapse').click(function () {
        app.trigger('mycustom-trigger', app);
    });

请在 sammy.js 中阅读有关 eventsrouting 的更多信息

祝你好运:)

【讨论】:

  • 你能给我一个演示吗?
  • 当然,您能否为您的 sammy-routing 提供一些代码 :)
  • 感谢您的回答和解释。我一定会试试这个。
【解决方案2】:

强制重新加载路由的一种更简单、更简洁的方法是调用Sammy.Applicationrefresh()method

import { sammyApp } from '../mySammyApp';

const url = `${mySearchRoute}/${encodeURIComponent(this.state.searchText)}`;
if (window.location.hash === url) {
    sammyApp.refresh();
else {
    window.location.hash = url;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-07
    • 2011-02-03
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多