如何处理在Backbone.js的一个简单的单击事件?(How to handle a simple

2019-10-17 13:11发布

我有东西在骨干非常简单的难度。 我想的电缆铺设工作<h1>在我的网页,这样,当用户点击它,它无缝地返回到首页,没有回传。

这是HTML:

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

(UPDATE:固定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的单击事件只是够了,但我想知道我应该如何在骨干网做它。

Answer 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});

});


Answer 2:

你的标签id是无效的,试试这个:

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


文章来源: How to handle a simple click event in Backbone.js?