Note that there are some explanatory texts on larger screens.

plurals
  1. POClick menu item to highlight in Backbone View
    primarykey
    data
    text
    <p>This is a simple problem for beginner but so far I haven't seen a solution that fits my need. Basically I got a simple menu with <code>ul</code> and <code>li</code>. There are 2 requirements:</p> <p><strong>Req1:</strong> When click on one, the <code>li</code> will get new class <code>.active</code>. </p> <p><strong>Req2:</strong> Menu items are dynamic, meaning I should be able to add or remove any menu item (by using some other button).</p> <p>There are <em>2 ways</em> to do this:</p> <p><strong>Method 1: Tranversing for each MenuView as MenuItem</strong></p> <p>I have a MenuView with something like this</p> <pre><code>el: $('li'), events: { "click" : "highlight" }, highlight: function(e) { thisParent = $(e.target).parent(); thisParent.siblings('.active').removeClass('active'); thisParent.addClass('active'); }, </code></pre> <p><strong>Pro:</strong> Easy. This is what I have now.</p> <p><strong>Con:</strong> Dependency on the html structure. What if it's changed to <code>div</code> instead with many layers.</p> <p><strong>Method 2: One View for the MenuCollection</strong></p> <p>Create a MenuItemCollection and use MenuView for that collection instead. The <code>el</code> for MenuView will be <code>ul</code> (instead of <code>li</code>). The HTML will look like this with separate <code>id</code>:</p> <pre><code>&lt;ul&gt; &lt;li id="leftmenu-one"&gt;one&lt;/li&gt; &lt;li id="leftmenu-two"&gt;two&lt;/li&gt; &lt;li id="leftmenu-three"&gt;three&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Then when a click event is detected, do 2 things:</p> <p><strong>2a.</strong> Remove all <code>.active</code> class in <code>ul li</code> </p> <p><strong>2b.</strong> Add <code>.active</code> class to the <code>e.target</code> DOM</p> <p><strong>Pro:</strong> Decoupling html design</p> <p><strong>Con:</strong> Little more code. </p> <p><strong>QUESTION:</strong> I think most people would say <strong>Method 1</strong> is bad. But is there method 3, 4, 5... that are better? How to handle the adding of new menu item?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload