How do you assign a static data- attribute to an ember view?
Asked Answered
C

2

5

I need to assign a static data- attribute to an Ember.View, how do I set that in the View object instead of in the {{view }} tag.

App.MessagesFormView = Ember.View.extend({
  tagName: 'div',
  classNames: ['modal', 'fade'],
  didInsertElement: function() {
    this.$().modal('show')
  },
  willDestroyElement: function() {
    this.$().modal('hide')
  },
})
Cozza answered 19/4, 2013 at 23:42 Comment(0)
B
6

Unfortunately, I don't have enough reputation to comment on Ola's answer, but I believe a slightly better way to do this is to not use a string (text in quotation marks) to denote the data attribute property name. Instead, write your property name in camelCase and Ember will automatically bind it to the hyphenated attributebinding. For example:

App.MessagesFormView = Ember.View.extend({
  tagName: 'div',
  attributeBindings: ['data-backdrop'], 
  dataBackdrop: 'static', // Binds to data-backdrop. Awesome!
});

I hope that makes sense!

Bracci answered 26/11, 2013 at 18:41 Comment(4)
For some reason, this didn't work for me. I agree that it seems like the Ember Way, but didn't do it (I am biding attributes within a Component, not a View, maybe that changes things?)Tiffanitiffanie
Maybe an update of Ember removed this functionality?Bracci
@DuncanWalker which version of ember are you using?Pheni
Now 1.9.1 but I'm not sure of the version I was using when the question was originally answered.Bracci
C
4

This has to be done using both an attributeBindings and data-backdrop or data-whatever property of the Ember.View object.

App.MessagesFormView = Ember.View.extend({
  tagName: 'div',
  classNames: ['modal', 'fade'],
  // Set a data attribute, of a view, requires both an attribute binding and
  // an attribute assignment
  attributeBindings: ['data-backdrop'],
  'data-backdrop': 'static',
  didInsertElement: function() {
    this.$().modal('show')
  },
  willDestroyElement: function() {
    this.$().modal('hide')
  },
})
Cozza answered 19/4, 2013 at 23:47 Comment(1)
Your example does the trick but does more than add a simple static attribute to the element. It will bind the attribute to the property value and will subsequently propagate property changes to the attribute, which may be an overkill for some use cases (bootstrap data-toggle anyone?). I suspect the only way to add a true static attribute is via this.$().attr('data-toggle', 'collapse') in didInsertElement.Guillot

© 2022 - 2024 — McMap. All rights reserved.