0

我在 Backbone 中遇到了一些非常简单的问题。我想<h1>在我的页面中连接,以便当用户单击它时,它会无缝返回到主页,而无需回发。

这是 HTML:

<h1><a id="home" href="/">Home</a></h1>

(更新:评论者建议的固定 ID。)这是我的主干视图和路由器:

var HomeView = Backbone.View.extend({
  initialize: function() { 
    console.log('initializing HomeView');
  },
  events: { 
    "click a#home": "goHome"
  }, 
  goHome: function(e) { 
    console.log('goHome');
    e.preventDefault();
    SearchApp.navigate("/");
  }
});
var SearchApp = new (Backbone.Router.extend({
  routes: { 
    "": "index", 
  },
  initialize: function(){
    console.log('initialize app');
    this.HomeView = new HomeView();
  },
  index: function(){
    // do stuff here
  },
  start: function(){
    Backbone.history.start({pushState: true});
  }
}));
$(document).ready(function() { 
  SearchApp.start();
});

控制台正在向我展示

initialize  app
initializing HomeView 

但是,当我单击 时<h1>,页面会发回 - 而我goHome在控制台中看不到。

我究竟做错了什么?显然,我可以<h1>在 jQuery 中简单地连接 click 事件,但我想了解我应该如何在 Backbone 中执行此操作。

4

2 回答 2

1

您的标签id无效,请尝试以下操作:

<h1><a id="home" href="/">Home</a></h1>
于 2013-01-07T15:39:50.303 回答
1

如果启用 pushState,则需要拦截所有点击并防止刷新:

$('a').click(function (e) {
  e.preventDefault();
  app.router.navigate(e.target.pathname, true);
});

就像是:

$(document).ready(function(){

  var HomeView = Backbone.View.extend({
    initialize: function() { 
      console.log('initializing HomeView');
    }
  });

  var AboutView = Backbone.View.extend({
    initialize: function() { 
      console.log('initializing AboutView');
    }
  });

  var AppRouter = Backbone.Router.extend({
    routes: { 
      "": "index", 
      "about":"aboutView"
    },

    events: function () {
      $('a').click(function (e) {
        e.preventDefault();
        SearchApp.navigate(e.target.pathname, true);
      });
    },

    initialize: function(){
      console.log('initialize app');
      this.events();
      this.HomeView = new HomeView();
    },

    index: function(){
      this.HomeView = new HomeView();
    },

    aboutView : function() {
      this.AboutView = new AboutView();
    }
  });

  var SearchApp = new AppRouter();
  Backbone.history.start({pushState: true});

});
于 2013-01-07T15:36:36.020 回答