Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an 'a' tag with a mailto href and bindAttr to a property?

I have a model, with a property 'contact_email'. I'd like to make a link with a mailto: href.

I've tried doing the slightly obvious <a {{bindAttr href="contact_email"}}>Email</a> but of course this is does not have the mailto: bit.

How can I combine mailto: with the property contact_email?

like image 358
Tony Pitale Avatar asked Jan 14 '13 02:01

Tony Pitale


Video Answer


2 Answers

At the moment, the only workable approach is to use a computed property (as you described in your comment).

One thing that might make this more tolerable, if you find yourself doing this often, is to create a computed property "macro":

App.computed.mailto = function(property) {
  return function() {
    return "mailto:" + this.get(property);
  }.property(property);
};

Then you could do this in your controller:

var mailto = App.computed.mailto;

App.UserController = Ember.ObjectController.extend({
  mailtoContactEmail: mailto('contactEmail')
});
like image 168
Yehuda Katz Avatar answered Oct 11 '22 14:10

Yehuda Katz


Register a simple bounded Ember Handlebars helper (Em.Handlebars.registerBoundHelper)

Em.Handlebars.registerBoundHelper('mailTo', function (emailAddress, label) {
    emailAddress = Em.Handlebars.Utils.escapeExpression(emailAddress);
    label = (arguments.length == 2) ? emailAddress : Em.Handlebars.Utils.escapeExpression(label);

    var link = '<a href="mailto:' + emailAddress + '">' + label + '</a>';
    return new Em.Handlebars.SafeString(link);
});

And use it like this:

simple mailto link:
{{mailTo emailAddress}} 
(output: <a href="mailto:[email protected]">[email protected]</a>)

mailto link with alternate label
{{mailTo emailAddress username}}
(output: <a href="mailto:[email protected]">foobar</a>)

Model used:

App.User = DS.Model.extend({
    username: DS.attr('string'),
    emailAddress: DS.attr('string')
});

Both values (the email address as well as the optional alternate label) are bounded to the model, and will change whenever the model changes.

Created a JSFiddle to demonstrate the changing model: http://jsfiddle.net/We6B9/

like image 30
s.meijer Avatar answered Oct 11 '22 15:10

s.meijer