31

I need to combine linkTo and action helpers in Ember.js. My code is:

{{#link-to 'index'}}<span {{action 'clear'}}>Clear</span>{{/link-to}}

But I would like to make this something like this:

{{#link-to 'index' {{action 'clear'}} }}Clear{{/link-to}}

And also:

<li>
    {{#link-to 'support'}}
        <span {{action 'myAction' 'support'}}>Support</span>
    {{/link-to}}
</li>

To:

<li>
    {{#link-to 'support' {{action 'myAction' 'support'}} }}Support{{/link-to}}
</li>

How can I achieve this?

Solution

Check my answer for Ember 2.0 compatible, OK for SEO solution.

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
  • 1
    Maybe a bit late but why you can't simply wrap your `link-to` helper in some other html element like `span` and fire the action you want there? Ej: ` {{link-to 'yourRoute'}} link text {{/link-to}} ` – Fabio Mar 01 '16 at 19:02
  • That would be 2 HTML elements instead of 1. Also, you would need to make change in CSS. If there's possibility to do that in 1 element and ok for seo then why not go for it? ;) And 1 more thing. What if you have like dozens or hundreds of such link-to's. That would be twice more HTML boilerplate then you need. – Daniel Kmak Mar 01 '16 at 19:03
  • Well, I just don't mind the 2 html elements hehe – Fabio Mar 01 '16 at 19:05

9 Answers9

30

Ember Link Action addon

This is OK for SEO solution!

Install addon

ember install ember-link-action

Usage

You can pass closure action as invokeAction param to {{link-to}} component:

{{#link-to 'other-route' invokeAction=(action 'testAction')}}
  Link to another route
{{/link-to}}

To pass parameters to action you can use:

{{#link-to 'other-route' invokeAction=(action 'testAction' param1 param2)}}
  Link to another route
{{/link-to}}

Compatibility

Automated test suite confirms that addon works with 1.13 up to latest Ember 3 releases.

It works with a release, beta and canary versions of Ember.

Addon GitHub repository. Contributions are welcome.

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
18

Update: See Michael Lang's comment below for Ember 1.8.1+

The problem with Myslik's answer (not using link-to at all but instead using an action and then transitionToRoute) is that it's useless for SEO, search engine bots will see nothing.

If you want what your link is pointing to to be indexed, it's easiest to have a good old <a href=x> in there. It's best to use link-to so that your link URLs are kept in sync with your route URLs. The solution I use gives both an action to do the work and a handy link-to to index the pages.

I override some functionality of Ember.LinkView:

Ember.LinkView.reopen({
  action: null,
  _invoke: function(event){
    var action = this.get('action');
    if(action) {
      // There was an action specified (in handlebars) so take custom action
      event.preventDefault(); // prevent the browser from following the link as normal
      if (this.bubbles === false) { event.stopPropagation(); }

      // trigger the action on the controller
      this.get('controller').send(action, this.get('actionParam'));
      return false; 
    }           

    // no action to take, handle the link-to normally
    return this._super(event);
  }
});

Then I can specify which action to take and what to pass the action in Handlebars:

<span {{action 'view' this}}>
  {{#link-to 'post' action='view' actionParam=this}}
    Post Title: {{title}}
  {{/link-to}}
</span>

In the controller:

App.PostsIndexController = Ember.ArrayController.extend({
  actions: {
    view: function(post){
      this.transitionToRoute('post', post);
    }
  }
}

This way, when I cache a rendered copy of the page and serve that to an indexing bot, the bot will see a real link with an URL and follow it.

(note also that transitionTo is now deprecated in favour of transitionToRoute)

Noland
  • 730
  • 6
  • 16
  • I'm not an SEO expert. But I've heard _briefly_ of Google's new way of indexing sites that use JS frameworks. If you had a setup to use the new JS SEO system, would they still be looking at the href attributes? – BJ McDuck Apr 20 '14 at 14:29
  • I would assume that any future/pending solution for at least the next few years would still look at the href attribute. Ignoring anchor tags would be a major change to the how the web is indexed. The above solution could possibly be made redundant if some some search bots find a brilliant way to run JS but I can't see it not working. – Noland Apr 24 '14 at 16:57
  • To perfect this great answer, it's best imho to also check if the link-to is disabled ( via this.get('_isDisabled') ) before invoking the action. – Andreas Andreou Jul 18 '14 at 17:18
  • 2
    Thanks for this answer! It appears the design of the link-to helper may have changed since this was posted though. In Ember 1.8.1, I had to replace this.get('controller').send(action, this.get('actionParam')); with this.sendAction('action', this.get('actionParam')); in order to get the action to propagate to my route's controller. – Michael Lang Jan 07 '15 at 01:19
17

None of these combinations will work in Ember.js, but you do not need to combine these two helpers. Why don't you just use action helper and let it bubble to controller or route? There you can use transitionToRoute in controller or transitionTo in route.

For example in controller you could have code like this:

App.PostsController = Ember.ArrayController.extend({
    clear: function () {
        // implement your action here
        this.transitionToRoute('index');
    }
});
Myslik
  • 1,178
  • 6
  • 14
9

This works fine in 1.6.0-beta.5:

<span {{action "someAction"}}>
  {{#link-to "some.route"}}
    Click Me
  {{/link-to}}
</span>

The link will happen and then the click will bubble up to the action handler. It's documented (albeit indirectly) here.

Edit: corrected syntax in opening link tag

AWM
  • 1,130
  • 11
  • 23
neverfox
  • 6,680
  • 7
  • 31
  • 40
7

I like Cereal Killer's approach for its simplicity, but unfortunately it exhibits a problem for me. When the browser navigates to another route, it restarts the Ember application.

As of Ember 2.6, the following simple approach does the trick:

<span {{action 'closeNavigationMenu'}}> {{#link-to 'home' preventDefault=false}} Go Home {{/link-to}} </span>

This achieves the following:

  • navigates to route 'home'
  • action 'closeNavigationMenu' is invoked
  • on mouseover, browser displays link that will be followed (for SEO and better UX)
  • browser navigation does not result in reboot of Ember app
bargar
  • 584
  • 5
  • 5
3

Having the same problem, i found this simple solution:

{{#linkTo eng.rent class="external-button"}}<div class="internal-button" {{action "updateLangPath"}} >X</div>{{/linkTo}}

then, managing the css classes external-button and internal-button in the stylesheet, i made sure that the "internal-button" was covering the whole "external-button" area; in this way it is not possible to click on the external-button without clicking on the internal-button.

It works well for me; hope it can help...

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
3

This is how I solved this in our demo application for the O'Reilly Ember.js book: https://github.com/emberjsbook.

You can see the complete source here: https://github.com/emberjsbook/rocknrollcall

In the view:

{{#if artistsIsChecked}}
  {{#if artists.length}}
    <h3>Artists</h3>

    <ul class="search-results artists">
      {{#each artists}}
        <li><a {{action 'viewedArtist' this.enid }}>{{name}}</a></li>
      {{/each}}
    </ul>
  {{/if}}
{{/if}}

And the controller:

App.SearchResultsController = Em.ObjectController.extend({
  actions: {
    viewedArtist: function(enid) {
      this.transitionToRoute('artist', enid);
    },
    viewedSong: function(sid) {
      this.transitionToRoute('song', sid);
    }
  },
  needs: ['artists', 'songs'],
  artistsIsChecked: true,
  songsIsChecked: true,
  artists: [],
  songs: []
});
jdcravens
  • 577
  • 1
  • 4
  • 15
2

This is what it would look like after Ember 3.11.0 with the on modifier.

<LinkTo
  {{on "click" this.recordMetrics}}
  @route="post.see-all"
  @model={{@model}}
  @bubbles={{false}}>
  Link Me
</LinkTo>

bubbles shown just to illustrate the LinkTo API.

https://blog.emberjs.com/ember-3-11-released/

snewcomer
  • 2,020
  • 1
  • 19
  • 22
  • Just ran into this issue again... And this solution does not work for me: adding the `{{on` modifier to the `LinkTo` component causes is to stop making the transition. Ember 3.28.6. – Andrey Mikhaylov - lolmaus Nov 15 '21 at 16:02
  • This works on 3.28.8 as I just added it to a project. I had to make sure the method I was calling had the action decorator, but seems to work great. – Cory Loken Jan 12 '22 at 02:19
0

Ember's link-to tags use routes to open new views, so you can perform whatever functionality you wanted to put in the link's 'action' attribute in the setupController method of the target route instead of in a controller action.

See here in the Ember guide: http://emberjs.com/guides/routing/setting-up-a-controller/

This only works if you want to perform the action every time the route is accessed, however, as opposed to with specific links.

Make sure to include the controller.set('model', model); line along with whatever else you put in there.

pvans
  • 1,017
  • 2
  • 10
  • 15