backbone view with dynamic id

2020-07-06 04:08发布

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.

3条回答
狗以群分
2楼-- · 2020-07-06 04:45

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});
查看更多
走好不送
3楼-- · 2020-07-06 04:47

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!

查看更多
家丑人穷心不美
4楼-- · 2020-07-06 04:47

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
       }
    }
})
查看更多
登录 后发表回答