Backbone: Can't Pass "data-" attributes within View's Attributes method

Created on 3 Oct 2012  路  8Comments  路  Source: jashkenas/backbone

I am a fan of setting attributes within a view as such...

Backbone.View.extend({
    attributes: {
        data-attr: 'mydata'
    }
});

... however, this throws an error due to the hyphen in the key "data-attr".

Uncaught SyntaxError: Unexpected token -
I realize this is an illegal token in a JavaScript key-value object, however I was hoping Backbone offered some work around for this, given the fact that passing data attributes is one of the most likely scenarios. I have been working around it by setting the attribute within the render function using jQuery:
render: function () {
    this.$el.attr( 'data-attr', 'mydata"');
}

This works, but I thought to ask if there is another option.

question

Most helpful comment

You can use a function like so:

attributes: function() {
  return {
    'data-attr': this.model.foo
  };
}

All 8 comments

Yep -- it's just a JavaScript object. Use quoted keys.

attributes: {
    "data-attr": "mydata"
}

Ahh, I thought I tried that! Thanks!

What do you suggest for passing a data attribute to the View's DOM element from the attributes within the View's Model? As such...

attributes: {
    "data-attr": this.model.foo
}

I am losing scope for reference to "this".

Uncaught TypeError: Cannot read property 'model' of undefined 

You can use a function like so:

attributes: function() {
  return {
    'data-attr': this.model.foo
  };
}

Awesome. That works perfectly. Thank you for the prompt responses!

You're welcome, but in the future, please don't use the bug tickets for tech support like this -- try the IRC channel or the mailing list first.

Happy to. I tried that first, but there is only one other user in DocumentCloud IRC, Turjakas who was not responding.

Must've mistyped -- there are 242 folks in #documentcloud on freenode right now.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sarkasm picture sarkasm  路  7Comments

etler picture etler  路  13Comments

azizZaben picture azizZaben  路  5Comments

tribalvibes picture tribalvibes  路  11Comments

jashkenas picture jashkenas  路  7Comments