Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add two new core methods to allow invoking possibly unknown methods on objects if they exist #1044

Merged
merged 1 commit into from
Jul 17, 2012

Conversation

devinus
Copy link
Member

@devinus devinus commented Jun 20, 2012

Rationale:

This is such a common idiom throughout Ember and my Ember apps:

var foo = get(this, 'foo');
if (foo && typeof foo.bar === 'function') {
  foo.bar();
}

...that I think it makes perfect sense to solidify the paradigm in Ember, especially when the code is less than 10 lines long total. Great code exposing good patterns in small chunks feels like the new thing Ember is trying to achieve. For instance: Ember.Evented.

I ask for naming suggestions as I don't particularly like tryToPerform.

Two possible alternatives already suggested include:

  • methodExists / invokeIfExists
  • canInvoke / tryInvoke

@travisbot
Copy link

This pull request passes (merged 3429efff into 1f8c983).

@travisbot
Copy link

This pull request passes (merged 4d4c36d7 into 1f8c983).

@jbrown
Copy link
Contributor

jbrown commented Jun 21, 2012

Do you have some links to places where this idiom exists in the Ember source?

@devinus
Copy link
Member Author

devinus commented Jun 25, 2012

@jbrown Sure. Take a look here: http://cloud.github.com/downloads/emberjs/ember.js/ember-latest.js

Do a Ctrl-F for "=== 'function'" or "'function' ==="

@devinus
Copy link
Member Author

devinus commented Jun 25, 2012

Any more discussion on the names?

@pangratz
Copy link
Member

pangratz commented Jul 6, 2012

👍

@devinus
Copy link
Member Author

devinus commented Jul 17, 2012

Renamed to canInvoke/tryInvoke as per @kselden's suggestion. These names are closer to existing Ember conventions, e.g trySetPath.

@travisbot
Copy link

This pull request passes (merged 2ffe666 into 20fb175).

wagenet added a commit that referenced this pull request Jul 17, 2012
Add two new core methods to allow invoking possibly unknown methods on objects if they exist
@wagenet wagenet merged commit 916da4a into emberjs:master Jul 17, 2012
@joliss
Copy link
Contributor

joliss commented Jul 24, 2012

For anyone using CoffeeScript, you can always write this:

@get('foo')?.bar?()

to yield

var _ref;

if ((_ref = this.get('foo')) != null) { // != checks for null or undefined
  if (typeof _ref.bar === "function") _ref.bar();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants