Reputation: 19969
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
Upvotes: 2
Views: 328
Reputation: 434785
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.
Upvotes: 1