New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can't Pass "data-" attributes within View's Attributes method #1703
Comments
Yep -- it's just a JavaScript object. Use quoted keys.
|
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. |
attributes on root elements (el) of FeatureItemViews and ValueItemViews (instead of misusing `render` function for this purpose). Aside from `class`, all attributes of feature and value items depend on properties of the model instance passed in when creating (instantiating) the corresponding View. As a consequence, they can not be set - at the top-level of the object passed to `Backbone.View.extend()` - inside an `attributes` *object*. If `attributes` is a *function*, however, it is run *after* any properties passed to a view's constructor are set, which makes it possible to generate attributes dynamically, based on the data passed in to the view's constructor. The view's `el` is created afterwards, based on the views `attributes`. --- Sources: - http://backbonejs.org/#View-attributes - "Setting id and className dynamically in Backbone.js views" @ http://stackoverflow.com/q/7033134/1199226 (relevant answer: http://stackoverflow.com/a/10337149/1199226) - "Can't pass 'data-' attributes within View's Attributes method" @ jashkenas/backbone#1703
I am a fan of setting attributes within a view as such...
... however, this throws an error due to the hyphen in the key "data-attr".
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:
This works, but I thought to ask if there is another option.
The text was updated successfully, but these errors were encountered: