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.
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 anaction
and thentransitionToRoute
) 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 uselink-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 handylink-to
to index the pages.I override some functionality of
Ember.LinkView
:Then I can specify which action to take and what to pass the action in Handlebars:
In the controller:
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 oftransitionToRoute
)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.