javascriptjqueryasp.netasp.net-mvcsammy.js

Reload the page using sammy.js


I am using sammy.js for single page application in asp.net mvc.
Everything is fine, but I am facing one problem which is that I can not reload the page.
For example When I am in the dashboard my URL is

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('#/');
    }
};
}

I want to reload the page by clicking the dashboard menu/link. But click event not firing because link is not changing. But if I want to go another page then it is fine. Please help me out. Thanks.


Solution

  • I think you have to append the same partial again. You can't "update" the partial in that meaning. As you say in your post, when you click another link and then back again it works.

    That's what you'll have to do. Append the same page/partial again, by doing that you clear all variables and recreate them, by that simulating a refresh.

    EDIT: Added example Observe that I didn't copy your code straight off but I think you'll understand :) And I don't use hash (#) in my example.

    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);
        });
    

    Please read more about events and routing in sammy.js

    Good luck :)