Backbone.js view id tag using information from model

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 the same view:

<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 got stuck when it came to putting the user id in 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 to put the current model ID in the id attribute?

+3


source to share


3 answers


First of all, your model has picture

, but your template uses image

, they must be the same or you will get a "missing variable" error from your template.

The attribute id

on the view must be the DOM of an id

existing element; Backbone won't add it to el

, Backbone uses it to find it el

. Also, this

it won't be displayed on run id: this.model.id

( this

probably will window

or some other useless thing) and the property model

won't be set until the view is created anyway.

the view el

is
:

created from the idea tagName

, className

, id

and property attributes if they are specified. If not, el is empty div

.



So, leave id

in your view and use the default <div>

for el

. Then in your method, render

you can set the attribute id

to this.el

; Also, using a numeric attribute id

causes problems with some browsers, so you usually have to prefix it id

with something non-numeric:

render: function() {
    this.el.id = 'v' + this.model.get('id');
    this.$el.append(this.template(this.model.toJSON()));
    return this;
}

      

Demo: http://jsfiddle.net/ambiguous/ZBE5z/

Open a console when you run the demo and you should be able to see the HTML that gets into your view this.el

.

+3


source


I am using this

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

      



U can only get model data with ". Get ()"

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

+5


source


This is because the model is not set when JavaScript is initially executed. Try the following:

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

      

0


source







All Articles