Change hash without triggering Sammy event

2019-06-15 10:46发布

function UsersVM(start_page){
  var self = this;
  console.log('start form ' + start_page);
  self.go_to = function(page) {
    location.hash = '#Users/' + pageNumber;     
  }
}

Sammy(function() {
    this.get('/app/?#Users/:page', function () {
        var vm = new  UsersVM(this.params.page);
        ko.applyBinding(vm);               
    });
}).run();

I would like to change the page's hash with the following code:

    location.hash = '#Users/' + pageNumber;

But in this case Sammy triggers routing. Say in Backbone we can do it this way:

    app.navigate("help/troubleshooting", {trigger: false}); 

Is it possible to do it in Sammy? Thanks!

2条回答
Melony?
2楼-- · 2019-06-15 11:33

Use the following code:

var new_location = '#foo';
app.trigger('redirect', {to: new_location});
app.last_location = ['get', new_location];
app.setLocation(new_location);
查看更多
\"骚年 ilove
3楼-- · 2019-06-15 11:42

I don't know of a native way to do this in Sammy, but here is a solution that has worked for me:

var sam = $.sammy(function () {
    var sammy = this; //get a persistent reference to this

    sammy.quiet = false; //set quiet to false by default

    //I set quiet to true before running a route
    sammy.quietRoute = function (location) {
        sammy.quiet = true;
        sammy.setLocation(location);
    }

    //I'm called after every route to reset quiet to false
    sammy.after(function () {
        sammy.quiet = false;
    });

    //I'm a 'normal' route that does not have the capability to be 'quiet'
    this.get('#normalRoute', function () { 
        //routing code 
    });

    //I am a route that can be 'quieted' so that when the url or 
    //hash changes my routing code doesn't run
    this.get('#quietableRoute', function () {
        if (!sammy.quiet) {
            //routing code
        } else {
            return;
        }
    });

});

Then call the quietRoute function in your code:

//This will work
sam.quietRoute("#quietableRoute");

//This will not work because the "if(!sammy.quiet)..." code has not been 
//implemented on this route
sam.quietRoute("#normalRoute");
查看更多
登录 后发表回答