【问题标题】:Change hash without triggering Sammy event在不触发 Sammy 事件的情况下更改哈希
【发布时间】:2013-01-04 13:30: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();

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

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

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

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

在 Sammy 中可以做到吗? 谢谢!

【问题讨论】:

  • 我也在想办法,你找到了解决方案@Andrew Luzkovky?

标签: javascript knockout.js sammy.js


【解决方案1】:

我不知道在 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");

【讨论】:

    【解决方案2】:

    使用以下代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多