2

I know this is not how you are supposed to do this but we have a legacy jQuery app and there has been some discussion of moving it to backbone. One idiom that would be appealing is something like this:

<script type="text/html" id="mi_form_template">
  the data-item-id is the value we are interested in!!!
 <button id="item" data-item-id='23'>here is item</button>
  </script>

I know that you are not supposed to store information like this in the DOM with backbone. But want to be able to anticipate the discussion about this.

Could I acces the item-id like this?

ItemsRouter = Backbone.Router.extend({
    routes: {
      "new": "newProduct",
      "": "index"
    },
    newProduct: function() {
      alert('here is newProduct');
      var item_id=$(this).data('item-id'); // <- can we do this???
      new ItemFormView( {model: new Item()});
    },
    ind ...

From preliminary tests, this won't work - it looks like the reference to this isn't working. Is this or something like this possible?

thx in advance

timpone
  • 19,235
  • 36
  • 121
  • 211

1 Answers1

1

Normally you'd access data attributes through a view (not a router) with something like this:

events: {
    'click #item': 'newProduct'
},
newProduct: function(ev) {
    var item_id = $(ev.target).data('item-id');
    // And now do whatever makes sense, possibly even trigger
    // a route that contains `item_id`.
}

A route handler doesn't know what triggered it, it just knows that it is supposed to handle a particular URL pattern. If you wanted to use a router for this sort of thing then you'd want a link:

<a href="/new/23">...</a>

and then in the router:

routes: {
    'new/:item_id': 'newProduct'
},
newProduct: function(item_id) {
    // Do things with item_id
}

So you can still use data attributes (which is okay with Backbone BTW) but you'd probably be accessing them in a view's event handlers rather than in a router.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • thx mu, just realized my mistake with the router and was going back to edit... is there any difference between ev.target and ev.currentTarget? It seems like we could use the idiom you mention above for replacing a lot of our jquery. thx again, I really appreciate. – timpone Nov 20 '12 at 06:58
  • @timpone: `target` and `currentTarget` aren't the same, `target` is more or less the thing that was clicked but `currentTarget` is the thing handling the delegation. There's a bit more information (including some links to demos) over here: http://stackoverflow.com/a/10078740/479863 – mu is too short Nov 20 '12 at 07:04