How to handle a simple click event in Backbone.js?

耗尽温柔 提交于 2019-12-12 01:23:13

问题


I am having difficulty with something very simple in Backbone. I want to wire up the <h1> in my page so that when the user clicks on it, it returns seamlessly to the homepage, without a postback.

This is the HTML:

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

(UPDATE: fixed ID as suggested by commenter.) And this is my Backbone view and router:

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

The console is showing me

initialize  app
initializing HomeView 

But when I click on the <h1>, the page posts back - and I don't see goHome in the console.

What am I doing wrong? Clearly I can wire up the <h1> click event simply enough in jQuery, but I want to understand how I should be doing it in Backbone.


回答1:


If you enable pushState you need to intercept all clicks and prevent the refresh:

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

Something like:

$(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});

});



回答2:


Your tag id is invalid, try this:

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


来源:https://stackoverflow.com/questions/14198959/how-to-handle-a-simple-click-event-in-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!