Магистральный маршрутизатор останавливает распространение

Это передняя часть позвоночника.

У меня есть этот шаблон на index.html

<script id="sportTemplate" type="text/template">
  <ul>
    <li><%%= title %>
    <a href="#sports/<%%=id%>/events" class="events">Life events</a>
    </li>
  </ul>
</script>

Тогда у меня есть маршрутизатор, который слушает

var appRoutes = Backbone.Router.extend({
  routes: {
   "sports/:id/events": "getEvents",
  },
(...)
});

Есть ли способ остановить распространение и заставить URL-адрес показывать только http://localhost:3000 вместо http://localhost:3000/#sports/100/events

Спасибо


person Gerard Morera    schedule 25.10.2015    source источник
comment
Непонятно, что вы спрашиваете. Если вы не хотите, чтобы URL-адрес менялся, не используйте маршрутизатор в первую очередь. Пожалуйста, подтвердите или уточните.   -  person Yura    schedule 25.10.2015
comment
Ты прав. Мое недоразумение. Я ожидал, что внутренние маршруты не будут отображаться в адресной строке, но, думаю, все в порядке. Спасибо   -  person Gerard Morera    schedule 26.10.2015


Ответы (1)


Лучшим способом обработки ссылок в приложениях Backbone является прослушивание событий кликов, особенно если вы не хотите, чтобы URL-адрес менялся.

var User = Backbone.Model.extend();
var Users = Backbone.Collection.extend({
  model: User,
  url: 'http://jsonplaceholder.typicode.com/users'
});

var UserView = Backbone.View.extend({
  tagName: 'li',
  template: _.template( $('#userTemplate').html() ),
  initialize: function(){
    _.bindAll(this, 'showPosts');
    this.posts = new Posts([], {
      url: 'http://jsonplaceholder.typicode.com/users/'+this.model.id+'/posts'
    });
  },
  events: {
    'click a.posts': 'openPosts'
  },
  render: function(){
    this.$el.html( this.template( this.model.toJSON() ) );
    return this;
  },
  openPosts: function(evt){
    evt.preventDefault();
    this.posts.fetch().done( this.showPosts );
  },
  showPosts: function(){
    userPostsView.showPosts(this.posts, this.model);
  }
});

var UsersView = Backbone.View.extend({
  tagName: 'ul',
  initialize: function(){
    this.listenTo( this.collection, 'add', this.addOne );
  },
  addOne: function(user){
    var userView = new UserView({ model: user });
    userView.render().$el.appendTo( this.el );
  }
});

var Post = Backbone.Model.extend();
var Posts = Backbone.Collection.extend({
  initialize: function(m, o){
    this.url = o.url;
  }
});

var PostView = Backbone.View.extend({
  template: _.template( $('#postTemplate').html() ),
  render: function(){
    this.$el.html( this.template( this.model.toJSON() ) );
    return this;
  }
});

var PostsView = Backbone.View.extend({
  initialize: function(){
    _.bindAll(this, 'addOne');
    this.listenTo(this.collection, 'add', this.addOne);
  },
  events: {
    'click .close': 'hide'
  },
  render: function(){
    this.collection.each(this.addOne);
    $('<a href="javascript:void(0)" class="close">[x]</a>').prependTo(this.el);
    $('<h3>Posts by '+this.model.get('name')+'</h3>').prependTo(this.el);
    return this;
  },
  addOne: function(post){
    var postView = new PostView({model:post});
    postView.render().$el.appendTo(this.el);
  },
  hide: function(){
    userPostsView.hide();
  }
});

var UserPostsView = Backbone.View.extend({
  initialize: function(){
    _.bindAll(this, 'hide', 'removePostsView');
  },
  showPosts: function(posts, user){
    this.$el.removeClass('hidden');
    if (this.postsView) this.postsView.remove();
    this.postsView = new PostsView({ collection: posts, model: user });
    this.postsView.render().$el.appendTo(this.el);
  },
  hide: function(){
    this.$el.addClass('hidden');
    this.setTimeout(this,removePostsView, 500);
  },
  removePostsView: function(){
    this.postsView.remove();
  }
});

var userPostsView = new UserPostsView({el:'#userPosts'});

var users = new Users();
var usersView = new UsersView({ collection: users });
usersView.render().$el.appendTo( document.body );
users.fetch();
#userPosts {
  position: absolute;
  background: rgba(255,255,255,0.95);
  min-height: 20px;
  left:10px;
  right:10px;
  border: 1px solid rgba(0,0,0,0.1);
  border-radius: 2px;
  padding: 5px;
  transition: 0.5s;
  visibility: visible;
  opacity: 1;
}

#userPosts.hidden {
  visibility: hidden;
  opacity: 0;
}

#userPosts>div>div {
  display:inline-block;
  max-width: 150px;
  max-height: 150px;
  vertical-align: top;
  overflow:hidden;
  margin:10px;
  font-size: 12px;
}
#userPosts p {
  margin: 0px;
  color: #ccc;
}
#userPosts .close {
  float:right;
}
h4 {
  margin: 0;
}
h3 {
  margin: 10px;
}
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
  
<script id="userTemplate" type="text/template">
  <%= name %>
  <a href="#" class="posts">User posts</a>
</script>
  
<script id="postTemplate" type="text/template">
  <h4>
    <%= title %>
  </h4>
  <p><%= body %></p>
</script>
  
<div id="userPosts" class="hidden"></div>

person Yura    schedule 26.10.2015