Swati February 2016

ember: how to convert anchor tag with href to link-to?

In our ember application, am having some strange requirement.

From the api, am receiving the message which has link to some other page in the same application.

For ex: "offers/1/checkout"

The message am receiving is:

"Thanks for the reply. <a href='offers/1/checkout'>Click here</a> to proceed further"

Now when we use above message, display it in template, and when User click on the Click Here link, the whole app reloads.

Is there any way to stop that reload of app? or can we convert simple href to link using link-to helper?

Thanks

Answers


EmberSherpa February 2016

You might want to look at this addon https://github.com/intercom/ember-href-to/blob/master/addon/helpers/href-to.js

Looking from the code, it has the mechanics to enable what you're looking for. If it doesn't work, setup a pairing session with me and I'll help you make it work.

http://j.mp/EmberSherpa


Swati February 2016

Many thanks to @ember-sherpa. From the reference he has given above https://github.com/intercom/ember-href-to/blob/master/addon/helpers/href-to.js#L14-L37

I have added a component as follows app/components/href-to-link.js

// Manually added anchor tags causes whole app to reload.
// This component will treat anchor tag as link-to links.
// Ex: <a href="/offers/1/plan_delivery"></a> will be trated as route "offers.plan_delivery"

import Ember from 'ember';

export default Ember.Component.extend({

  _getNormalisedRootUrl: function(router) {
    var rootURL = router.rootURL;
    if(rootURL.charAt(rootURL.length - 1) !== '/') {
      rootURL = rootURL + '/';
    }
    return rootURL;
  },

  didInsertElement() {
    var _this = this;
    var router = this.container.lookup("router:main");

    Ember.$().ready(function (){
      Ember.$(".received_message, .my_message").on('click', 'a', function(e) {
        var $target = Ember.$(e.currentTarget);
        var handleClick = (e.which === 1 && !e.ctrlKey && !e.metaKey);

        if(handleClick && !$target.hasClass('ember-view') && Ember.isNone($target.attr('data-ember-action'))) {

          var rootURL = _this._getNormalisedRootUrl(router);
          var url = $target.attr('href');

          if(url && url.indexOf(rootURL) === 0) {
            url = url.substr(rootURL.length - 1);

            if(router.router.recognizer.recognize(url)) {
              router.handleURL(url);
              router.router.updateURL(url);
              return false;
            }
          }
        }
        return true;
      });
    });
  }

});

Using it as:

{{#href-to-link}}
  ...
{{/href-to-link}}

This works perfectly fine!! Hope this will help others too :)

Post Status

Asked in February 2016
Viewed 2,981 times
Voted 7
Answered 2 times

Search




Leave an answer