Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model attribute name in Backbone

Tags:

backbone.js

I have a model given by a REST API and one of the name's attributes is like this:

defaults: {
...
"user-name" : "",
...
}

Then when I try to render it in a template by this way:

<script type="text/template" id="list">
<strong>User name: </strong>    <%= user-name %>
</script>

I have no problem to render the other attributes, but with this, it only recognise the first part of the name 'user' and consecuently it gives an error. Is there any way to change the name when you render or to escape the symbol '-', so the template recognise it?

Thank you!


2 Answers

The - isn't a valid variable character, so you'll have to change user-name to something else.

If you can't change the attribute throughout the model, and you're passing the model attributes to the template simply by calling model.toJSON(), you can change that variable just before passing it to the template:

var attrs = model.toJSON();
// change user-name to something else
attrs.user_name = attrs['user-name'];
// and delete it
delete attrs['user-name'];
// pass attrs to the template like normal
// ...
like image 158
freejosh Avatar answered Jan 29 '26 01:01

freejosh


You can wrap the data to an additional object and use the bracket indexer syntax. So, instead of:

_.template("<%= user-name %>", {"user-name": "..."} );

You can use:

_.template("<%= model['user-name'] %>", { model: {"user-name": "..." } } );
like image 30
jevakallio Avatar answered Jan 28 '26 23:01

jevakallio