3
votes

What i want is to handle the anchor button click inside my Marionette.ItemView events. I don't want to use href in anchor tag. I want to handle the click in my itemview and ask the backbone approuter to change page.

I want to switch my page from index to myaccount on an anchor button click. My template looks like below

<div>
    <a data-role="button" id="btn_eclipse" class="btn_eclipse_myaccount"><%= val_btn_myaccount %></a>
    <a data-role="button" id="btn_eclipse" class="btn_eclipse_services"><%= val_btn_services %></a>
    <a data-role="button" id="btn_eclipse" class="btn_eclipse_offers"><%= val_btn_offers %></a>
</div>

My Marionette.ItemView capture events like this

events : {
    'click input[type="button"]' : 'onButtonClick',
    'blur input[type="text"]' : 'onKeyPress',
    'click a' : 'onAnchorButtonClick',
},          
onAnchorButtonClick : function(obj){
    obj.preventDefault;
    var btn_id = $(obj.target).attr('id');
    console.log("The button clicked id is==="+$(obj.target).attr('id'));
    //here i trigger event to change page
}

I am not able to retrieve that ID or any other attribute like href as you specified in your answer from the anchor tag.

Please advice what should i do.

Thanks in advance.

2

2 Answers

4
votes

You can do what you want with something like this:

var MyView = Backbone.Marionette.ItemView.extend({
  events : {
    "click a" : "handleRouting"
  },

  handleRouting : function (e) {
    e.preventDefault();
    Backbone.history.navigate(/*whatever your route is*/, true);
  }
});

While the above will work, what I would instead recommend is doing what you don't want to do, namely use the href on the a tag and have a global listener that hooks into the routing.

Per your comment question, you can implement a global listener with something like the following:

$(document).on("click", "a", function (e) {
  var href = $(this).attr("href");
  if (href && href.match(/^\/.*/) && $(this).attr("target") !== "_blank") {
    e.preventDefault();
    Backbone.history.navigate(href, true);
  }
});

If you are using the HTML push API (rather than #!s) then something like the above will capture link clicks that route them through your Backbone.Router.

0
votes

I have implemented a behavior to take care of this automatically using the v-href attribute

https://github.com/samccone/marionette-behaviors#viewlinks

I use this extensively in all of my apps, and it works like a charm!