Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js view id tag using information from model

Tags:

backbone.js

I am using backbone.js,

I have a model that is formatted like this:

{
  username:"name",
  id:"1",
  picture:"image.jpg"
}

I want to have a view like this:

<div id="1">
    <span class="name">name<span>
    <img src="image.jpg" />
</div>

from this template:

<script type="text/template" id="users-template">
    <span class="name"><%= username %></span>
    <img src="<%= image %>" />      
</script>

but I get stuck when it comes to putting the users id into the views id attribute.

UserView = Backbone.View.extend({

    id: this.model.id, //this is what I have tried but it doesnt work

    initialize: function(){
        this.template = _.template($('#users-template').html());
    },

    render: function(){
        ...
    }
})

does anyone know how put the current models id into the id attribute?

like image 572
jamcoupe Avatar asked Mar 19 '26 15:03

jamcoupe


1 Answers

I use that

id : function () { 
    return this.model.get("id");
}

U can get the model's data only using ".get()"

Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime. @from Backbonejs.org

like image 146
Sergey Tytarenko Avatar answered Mar 21 '26 08:03

Sergey Tytarenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!