简体   繁体   中英

Registering Handlebars string comparison helper in Ember.js not working

I'm trying to implement a string comparison helper in my ember app and I keep getting this error :

Uncaught Error: Assertion Failed: A helper named if_eq could not be found

I can't believe it's that complicated to compare 2 strings together, it should be a basic but seems like it's not the case. So where am I wrong? Should I use something else to compare the strings?

Template :

{{#if_eq selectedConv.status 'opened'}}
  <button><span class="close">Close</span></button>
{{else}}
  <button><span class="close">Open</span></button>
{{/if_eq}}

Helper (directly in js file)

Handlebars.registerHelper('if_eq', function(a, b, opts) {
if(a == b) // Or === depending on your needs
    return opts.fn(this);
else
    return opts.inverse(this);
});

It's probably a better idea to have a computed property on the selectedConv object like isOpened . This is quite easy to do and a re-usable option if needed elsewhere in your app. Just add this additional code to the definition of selectedConv :

isOpened: Ember.computed('status', function () {
  return Ember.get(this, 'status') === 'opened';
})

This will allow you to simplify your template to this:

{{#if selectedConv.isOpened}}
  <button><span class="close">Close</span></button>
{{else}}
  <button><span class="close">Open</span></button>
{{/if}}

More information about computed properties to help you get started can be found in the Ember Guides .

If you insist on using conditional helpers, you are probably better off using a library that is already readily available like Ember Truth Helpers .

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