简体   繁体   中英

How to observe multiple states in a handlebar template from an ember controller or component

I'm new to ember and am struggeling with the typical "how would one do that"-Problem. What I've got is fairly simple and I know how to do it, but my way is so complicated that I do not think it's correct.

The case:

<ul>
  <li>{{link-to top-level}}</li>
  <li>{{link-to another-top-level</li>
  <ul class="submenu">
     <li>{{link-to submenu</li>
  </ul>
</ul>

What should happen is:

  • When a route is clicked, the corresponding list element should become active.
  • When a submenu is clicked the corresponding upper ul-element should get the class open

It's a fairly simple case with jQuery, but I understand that this is not scalable and abstracted and stuff.

Therefore I started with this approach:

  • Create a controller / template construct for the entire navigation to handle it's state (there are some other things I need to check as well, so it came in handy).

  • since ember adds the active class to the anchor tag I created a component to observe that:

Like:

export default Ember.Component.extend({
  tagName: 'li',
  classNameBindings: ['active'],

  active: function() {
      return this.get('childViews').anyBy('active');
  }.property('childViews.@each.active') 
});

Replacing the li elements with {{linked-list}} does indeed work.

But what next? Do I need to add another component to watch the component to watch the build in behaviour of active links? Do I have to write dedicated MVC-Classes for all the DOM Elements?

There has to be a simpler way, I think. I already created a whole lotta files for such a simple behaviour that I'm thinking I'm totally on the wrong track.

My gut feeling is: That is view logic and the view should just observe a few states in the template and that's it.

What's the leanest approach to the problem?

I don't know if I understand your question right, but why you want to add the class open to the corresponding upper element? It automatically get active assigned. And with correct CSS it should work as expected.

I have created a small example demonstrating what I mean. Please have a look and let me know, if that's the solution for you or what's your problem with this solution.

http://emberjs.jsbin.com/wifusosadega/7/edit

EDIT

Here is a Bootstrap flavored version: http://emberjs.jsbin.com/wifusosadega/9/edit .

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