1

I have a computed property on a view that is used to set a class on the view, and the property is calculated using the content of the view. If I do this the straightforward way and just do

App.SomeObj = Ember.Object.extend({
    name: 'hello'
})

App.SomeView = Ember.View.extend({
    classNameBindings: [ 'calculatedProperty:cssProp' ],

    calculatedProperty: function() {
        return App.SomeObj.get('name') === this.$()
    }.property('App.SomeObj.name')
})

Then I get this error:

Uncaught Error: Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.

(Example: http://jsbin.com/zazefato/1/edit) (Look in the Javascript console to see errors)

I can fix that problem by hooking the insertion of the element and manually calculating the property like this:

App.SomeView = Ember.View.extend({
    classNameBindings: [ 'calculatedProperty:cssProp' ],

    didInsertElement: function() {
        this.observeProperty()
        this.notifyPropertyChange('calculatedProperty')
    },

    observeProperty: function() {
        this.set('calculatedProperty', App.SomeObj.get('name') === this.$().text())
    }.observes('App.SomeObj.name') // recalculates on property change
})

However this is hacky and I think it is not the best way to do it. What is a better way to do this?

  • Do you want to use an input html element. Ember has a input helper whose implementation provides some useful utilities. Your input component will have its text value bound to its view value property in order you can setup any computed properties based on its value. May you take a look at it? I can help you if you have any problem with, please update your http://emberjs.jsbin.com/. – ppcano May 26 '14 at 08:46

1 Answers1

0

The jQuery object is returned from the $ method only after the view is rendered. Before then it is null.

Your computed property uses jQuery object in it's comparison. I believe such approach is not very good.

I think you have a flaw in the whole concept of what you are trying to achieve. If you could provide a clearer explanation of what is it you trying to achieve then the answer could direct you in the way things are done in Ember.

Denzo
  • 431
  • 1
  • 4
  • 15
  • I have a list which is generated by an `#each` helper in handlebars. Each of these elements have events for clicking and hovering, so they each represented by a view. I need to apply a CSS class to the element whose contents are equal to something (e.g. a global variable). That is what I am trying to do. – user3450921 May 27 '14 at 03:42
  • Check out this question http://stackoverflow.com/questions/23867677/how-to-display-posts-delete-button-for-only-posts-author-in-ember-js and if it doesn't help you then could you please ask another question because I don't know where to put the answer :( – Denzo May 28 '14 at 01:33