页面重新加载后,指向嵌套资源的链接将丢失活动类

Link to nested resource loses active class after page reload

本文关键字:链接 资源 嵌套 活动 新加载 加载      更新时间:2024-04-08

这些天我在学习ember,遇到了一个链接到helper的问题。如果我使用它为嵌套路由创建链接,它可以很好地工作(如果单击链接,"活动"类将添加到元素中,如文档中所述),直到我重新加载页面。当我重新加载页面时,嵌套唤醒的内容将正确加载到{{outlet}},但链接将丢失其"活动"类。我做错了什么?

JavaScript:

window.App = Ember.Application.create({ rootElement: '#app' });
App.Router.map(function () {
  this.resource('notes', { path: '/' }, function () {
    this.route('show', { path: '/:note_id' });
  });
});
App.NotesRoute = Em.Route.extend({
  model: function () {
    return App.Note.find();
  }
});
App.NotesShowRoute = Em.Route.extend({
  model: function (params) {
    return App.Note.find(params.note_id);
  }
});
App.Note = Em.Object.extend();
App.Note.reopenClass({
  find: function(id) {
    var notes = [
      {
        id: 1,
        title: 'abc',
        text: 'lorem ipsum text 1111111'
      },
      {
        id: 2,
        title: 'def',
        text: 'lorem ipsum text 2222222'
      }
    ];
    return id ? notes[parseInt(id) - 1] : notes;
  }
});

HTML:

<div id="app" class="row">
    <script type="text/x-handlebars">
      <div class="col-md-2">
        <h2>Tags</h2>
      </div>
      {{outlet}}
    </script>
</div>
<script type="text/x-handlebars" data-template-name="notes">
    <div class="col-md-3">
      <h2>Notes</h2>
    {{#each}}
      {{#link-to 'notes.show' this}}{{title}}{{/link-to}}
    {{/each}}
    </div>
    {{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="notes/show">
    <div class="col-md-7">
      <h2>{{title}}</h2>
      <p>{{text}}</p>
    </div>
</script>

当您单击到的链接时,它会将对象传递到新路由。因此不调用模型查找。因此,演出路线的上下文和链接的对象都指向同一个对象。因此,它将被标记为活动。

但是,当您刷新页面时,您要进行两次查找,一次在NotesRoute模型中(每次循环),一次是在NotesShowRoute模型。

Javascript对象是引用类型。两个普通的javascript对象被认为是不相等的,即使它们的内容是相同的。例如,尝试在javascript控制台中键入此内容。

{ one: 1, two: 2} == {one: 1, two: 2}

因此,链接中引用的对象与当前路线的模型不同。因此,对处于活动状态的链接进行相等性检查将不起作用。

快速解决方案是每次都阻止find创建对象。例如

App.Note.reopenClass({
  all: [
    {
      id: 1,
      title: 'abc',
      text: 'lorem ipsum text 1111111'
    },
    {
      id: 2,
      title: 'def',
      text: 'lorem ipsum text 2222222'
    }
  ],
  find: function(id) {
    return id ? this.all[parseInt(id) - 1] : this.all;
  }
});

另一种选择是为对象滚动某种身份映射。这是一篇博客文章,做了一个比我能解释的更好的例子

请注意,我还没有真正测试过该代码,因为我太懒了,无法创建jsbin。但如果不起作用,请告诉我。