更改哈希而不触发Sammy事件

时间:2013-01-04 13:30:47

标签: javascript knockout.js sammy.js

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

我想用以下代码更改页面的哈希值:

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

但在这种情况下,Sammy会触发路由。在Backbone中说我们可以这样做:

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

有可能在Sammy做到吗? 谢谢!

2 个答案:

答案 0 :(得分:5)

我不知道在Sammy中这样做的本地方法,但这是一个对我有用的解决方案:

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

});

然后在代码中调用quietRoute函数:

//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");

答案 1 :(得分:0)

使用以下代码:

var new_location = '#foo';
app.trigger('redirect', {to: new_location});
app.last_location = ['get', new_location];
app.setLocation(new_location);
相关问题