Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone view with dynamic id

I just realized I was misunderstanding the el attribute of a Backbone.View. Basically my views require dynamic id attributes based on its model's attribute. I thought I had this working fine because I simply specified it in my template:

<script type="text/template" id="item_template">
  <li class="item" id="{{identifier}}">
    <span class="name">{{name}}</span>
  </li>
</script>

However, I realized that what Backbone was actually doing was putting this compiled template into another element, div by default. I learned more about this by reading the documentation, but I'm still confused on how to create a dynamic id.

Preferably, I would love to find a way to make it such that the stuff in the above template serves as my el, since it already has everything I want, but I don't know if that is possible. So I'm wondering if, quite simply, there is a way to specify a dynamic id attribute.

I tried setting it within the initialize method, this.id = this.model.get('attr') but it didn't seem to have any effect, possibly because by this time it is already too late.

What I'm currently doing is just using jQuery to add the id in during render():

this.el.attr(id: this.model.get('identifier'));

it works, but of course, I'm simply asking if there is a preferred way to do it through Backbone.

like image 578
Jorge Israel Peña Avatar asked Nov 21 '11 08:11

Jorge Israel Peña


3 Answers

Yes there is a standard way to do this in Backbone. You can pass id to the View constructor. You can also refactor your template so that Backbone creates the parent <li> element for you. Try this simpler template:

<script type="text/template" id="item_template">
  <span class="name">{{name}}</span>
</script>

And add these to your view:

myView = Backbone.View.extend({
  className: "item",
  tagName: "li"
})

And instantiate it like this:

var view = new YourView({
  model: mymodel,
  id: mymodel.get('identifier') // or whatever
})

Good luck!

like image 135
maxl0rd Avatar answered Oct 19 '22 17:10

maxl0rd


There is one more approach. I found it more convenient than passing id every time you create an instance of your view.

Template:

 <script type="text/template" id="item_template">
      <span class="name">{{name}}</span>
 </script>

View:

var MyView = Backbone.View.extend({
    tagName: 'li',
    attributes: function(){
       return { 
           id: this.model.get('identifier'),
           class: 'item'//optionally, you could define it statically like before
       }
    }
})
like image 5
evilive Avatar answered Oct 19 '22 18:10

evilive


When you create your view, pass in a selector that will let the view find your existing pre-rendered DOM element:

var id = "1234";
var view = YourView({el: '#'+id});
like image 1
dmnd Avatar answered Oct 19 '22 17:10

dmnd