简体   繁体   中英

Share buttons for different templates in ember.js

I have multiple models each of which has its own template. I want to share a footer of buttons accross the different templates so when the same button is pressed different functions are executed according to the selected template. The HTML looks like this:

    <script type="text/x-handlebars" id="application" >
       <menu>
          <nav>
             <ul>
               <li>{{#link-to 'model1'}}Model 1{{/link-to}}</li>
               <li>{{#link-to 'model2'}}Model 2{{/link-to}}</li>
               <li>{{#link-to 'model3'}}Model 3{{/link-to}}</li>
             </ul>
          </nav>
       </menu>

       <div class="content">
         <section>
           {{outlet}}
         </section>
       </div>

      <footer>
        <ul>
          <li><button class="action-undo" {{action undo}}>Undo</button></li>
          <li><button class="action-save" {{action save this}}>Save</button></li>
          <li><button class="action-saveContinue" {{action saveAndContinue this}}>Save & Continue</button></li>
        </ul>
      </footer>
    </script>

You probably want to use the {{partial}} helper. It will inline a template (with the same context) when it is called.

To use the partial helper just create a template with a leading underscore, like : _buttons . To include that template you can now use {{partial "buttons"}} .

See: http://emberjs.com/guides/templates/rendering-with-helpers/

You can keep the application template with the footer so all templates inserted in the outlet will have the footer.

To get the actions triggering to some corresponding template, just override the route of that template, for example in the model1 template, you can create a App.Model1Route implementing the actions:

App.Model1Route = Ember.Route.extend({
    actions: {
        undo: function() {
            // perform undo
        },
        save: function() {
            // perform save
        },
        saveAndContinue: function() {
            // perform save and continue
        }
    }
});

And for model2 template just override the App.Model2Route and add the actions to be triggered in that template, and so on.

Give a look in that fiddle to see this working http://jsfiddle.net/marciojunior/d3xA6/

Be careful because if some route don't implement some triggered action, an error is raised. In that case you can extract your footer to a partial and just add where is used.

I hope it helps

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