简体   繁体   中英

Ember.js How to bind isSelected class to the clicked view?

I have some views which will expand and show details when clicked.

For now, all the views can be clicked and expand, but the question is

How to expand only the latest clicked view?

For example, when I clicked view #1, it expand. So when I clicked view #2, the view #1 will collapse and view #2 expand etc.

I know we can bind a isSelected classname to the clicked view, but how do we tell the view to check "If any other view is selected" ?

Do we use CollectionView ? But how?

FYI this is the working JSBin .

First of all, I would change view to component . Although views have their valid use-cases, you are usually better off with a component.

Also, if you think about it, it makes sense that someone outside of the component would need to know which component was clicked last. That outside actor could be the controller, which could have a property called lastComponentClicked (which initially starts out as null )

App.IndexController = Ember.ArrayController.extend({
  lastClickedComponent: null
});

Then, you can pass that property into each component and the property becomes bound between the controller and all the components as in:

  <script type="text/x-handlebars" data-template-name="index">
    {{#each content in model}}
      {{ x-box content=content lastClickedComponent=lastClickedComponent}}
    {{/each}}
  </script>

So far, so good. Now, for the component itself:

App.XBoxComponent = Em.Component.extend({
  classNames: ['box'],
  isSelected: function(){
    return this.get('lastClickedComponent') === this._uuid;
  }.property('lastClickedComponent'),

  click: function(){
    this.set('lastClickedComponent', this._uuid);
  }  
});

Every time it is clicked, you can set a lastClickedComponent property, which is bound between ALL the components and the controller and thus will get reset every time. You can just set it to a value unique to the component, for example this._uuid .

isSelected computed property can then just check if lastClickedComponent property is that of THIS component, in which case the content you need to show will be expanded.

  <script type="text/x-handlebars" id="components/x-box">
    {{content}}

    {{# if isSelected }}
      <div>LAST SELECTED</div>
    {{/if}}
  </script>

Working solution here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM