简体   繁体   中英

Service, get & extend in javascript and how are they being used

I am trying to make sense of some code snippets in javascript. But getting way too confused, it seems to be using all the symbols in all possible ways.

import Ember from 'ember';

export default Ember.Route.extend({
  metrics: inject.service(),

  activate() {
    this._trackPage();
  },

  _trackPage() {
    run.scheduleOnce('afterRender', this, () => {
      const page = document.location.href;
      const title = this.routeName;

      get(this, 'metrics').trackPage({ page, title });
    });
  }
});

q1: What are the keyword service, get, extend? What are they doing here? q2: Why is activate defining _trackPage separately? Why not put the reschedule code in activate() itself?


Basically trying to understand: https://emberway.io/applying-the-adapter-pattern-for-analytics-in-ember-js-apps-29448cbcedf3


A service is a place to put code that can be used almost anywhere in the app. In order to make the code inside a service available to the script you're working on, you inject it.

get is a helper that is used to access things like the service or Ember objects. In more recent tutorials, you'll see syntax that looks more like this.get('metrics') . See the docs here .

You could put the _trackPackage code into the activate function if you wanted to. However, activate is a special function called a hook, and many developers like to keep their route hooks like activate as short and sweet as possible for stylistic reasons. Hooks are special functions that fire automatically on things like a user entering a route, rerenders, etc. There are many kinds of hooks like this throughout Ember.

Extend is Ember boilerplate that gets created for you when you use the Ember CLI to make new files. Basically, when you create a route, you're extending on Ember's default route configurations, attributes, and methods. So there's some base behavior (like the activate hook) that gets inherited.

I recommend that you read the Ember Guides sections on objects and services for more info.

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