使用弹片路由敲除 JS 参数

Knockout JS parameters with Grapnel routing

本文关键字:JS 参数 路由      更新时间:2023-09-26

我正在开发一个淘汰赛应用程序,现在需要实现路由。Grapnel 看起来是一个很好的解决方案,但我用它撞到了一点砖墙。

挖空点击事件将当前的"视图模型"传递给您在视图中定义的任何函数 - 如此处所述。如前所述,这在使用集合时非常有用,我提到的应用程序经常使用它。

我正在寻找一种能够从 grapnel 路线中使用它的方法,但是当涉及到解决方案时,我迷失了方向。

我整理了一个相当简单的小提琴来帮助解释事情:https://jsfiddle.net/nt0j49x7/4/

.HTML

<div id="app">
  <ul class="playlist" data-bind="foreach: albumList">
    <li class="album">
      <a href="" data-bind="click: $root.showAlbumInfo">
        <span data-bind="text: title"></span> -
        <strong data-bind="text: artist"></strong>
      </a>
    </li>
  </ul>
  <div data-bind="with: selectedAlbum">
    <img data-bind="attr:{src: coverImg}" />
    <div>
      <span data-bind="text: title"></span> - <span data-bind="text: artist"></span> 
      <a data-bind="attr:{href: spotifyLink}">Listen on spotify</a>
    </div>
  </div>
</div>

爪哇语

var appView = {
    albumList: ko.observableArray([
    {id: 1, title:'Helioscope' , artist: 'Vessels', coverImg: 'http://ecx.images-amazon.com/images/I/91nC-KVZBBL._SX466_.jpg', spotifyLink: 'https://open.spotify.com/album/3dARFB98TMzKLHwZOgKZhE'},
    {id: 2, title:'Dilate' , artist: 'Vessels', coverImg: 'http://ecx.images-amazon.com/images/I/31AvNaBtnpL._SX466_PJautoripBadge,BottomRight,4,-40_OU11__.jpg', spotifyLink: 'https://open.spotify.com/album/7yapNLdtqlYiGFbuEuGRIt'},
    {id: 3, title:'White fields and open devices' , artist: 'Vessels', coverImg: 'http://ecx.images-amazon.com/images/I/918vEDkM5PL._SX522_PJautoripBadge,BottomRight,4,-40_OU11__.jpg', spotifyLink: 'https://open.spotify.com/album/4kB1vlgei2DvIweeBoiNVu'}
  ]),
  selectedAlbum: ko.observable(),
    showAlbumInfo: function(album, event) {
    // knockout supplies the clicked model value as the first parameter
    appView.selectedAlbum(album);
  }
};
var routes = {
        'album/:id' : function(req, event){
            // Any ideas on how to pass the 'album' object knockout is
      // passing to the appView.showAlbumInfo method into this
      // route handler? I can use the ID request param to
      // get the model from albumList and set the selectedAlbum
      // but that isn't what I'm trying to achieve.
        }
};
//var router = new Grapnel(routes);
ko.applyBindings(appView, document.getElementById('app'));

我已经使用淘汰赛一年了,但只是快速浏览了一下 Grapnel。我没有看到将对象作为参数传递的方法。 但这显然是一种单页应用方法,您已将视图模型声明为全局模型。 因此,您可以访问路由器代码中的"appView":

var router = new Grapnel();
//must include the id in the route for function to fire on id change
router.navigate('/album/' + album.id);
            console.info(appView.selectedAlbum());
        }
);

然后在 viewModel 事件中,您可以在设置可观察量后进行导航。

showAlbumInfo: function(album, event) {
    // knockout supplies the clicked model value as the first parameter
    appView.selectedAlbum(album);
    router.navigate('/album/' + album.id);
}

小提琴:示例不确定您的应用程序会是什么,但 Angular js 将完成您尝试在一个具有可观察量和路由的包中执行所有操作。 你不需要淘汰赛。