Confused about having to use window.variableName in my code and not understanding the reason

Working on a web app with JS, Angular, and Meteor that integrates the Youtube API has been quite challenging. In one of my controllers, I initialized the youtube player object in the constructor following the necessary steps outlined by the Youtube API. However, I encountered an issue where referencing the supposedly global "player" object in a later function within the same controller seemed to be out of scope.

I spent several days trying to figure out why the "player" variable, which appeared global (due to the lack of var declaration), was not accessible within the controller. It wasn't until I stumbled upon the discouraged practice of using window.variableName that I managed to make the playPause function recognize the player object by using window.player = ... Does anyone have insights into why the player object isn't inherently global within its containing controller and functions?

As I continue to navigate through javascript scoping nuances and ECMA class style, any assistance would be greatly welcomed.

Snippet of my code:

import Ionic from 'ionic-scripts';
import { _ } from 'meteor/underscore';
import { Meteor } from 'meteor/meteor';
import { MeteorCameraUI } from 'meteor/okland:camera-ui';
import { Controller } from 'angular-ecmascript/module-helpers';
import { Chats, Messages } from '../../../lib/collections';

export default class ChatCtrl extends Controller {
  constructor() {
    super(...arguments);
    this.currentVideoId = this.$stateParams.videoId;
    this.chatId = this.$stateParams.chatId;

    this.isIOS = Ionic.Platform.isWebView() && Ionic.Platform.isIOS();
    this.isCordova = Meteor.isCordova;
    chat = Chats.findOne(this.chatId);

    if (chat.playerType == "Y") {
      window.player = new YT.Player('video-placeholder', {
        videoId: this.currentVideoId,
        events: {
                  'onReady': this.initTimes.bind(this)
              }
      });
    } else if (chat.playerType == "V") {

      var options = {
        id: this.currentVideoId,
        width: 640,
        loop: false
      };

      var player = new Vimeo.Player('vimeo-placeholder', options);
    }

  playPauseToggle() {
    if (player.getPlayerState() == 2 || player.getPlayerState() == 5) {
      player.playVideo();
      this.playPauseValue = "Pause";
    } else if (player.getPlayerState() == 1) {
      player.pauseVideo();
      this.playPauseValue = "Play";
    }
  }

ChatCtrl.$name = 'ChatCtrl';
ChatCtrl.$inject = ['$stateParams', '$timeout', '$ionicScrollDelegate', '$ionicPopup', '$log'];

Answer №1

The issue here lies in the fact that you have defined your player as a local variable within your class constructor, limiting its visibility to only that function and not allowing access elsewhere, such as in your playPauseToggle function.

Instead, consider making your player an attribute of your class instance for broader accessibility.

this.player = new YT.Player('video-container'...

and then

playPauseToggle() {
    if (this.player.getPlayerState() == 2 || this.player.getPlayerState() == 5) {
    ... // make sure to replace all instances of 'player' with 'this.player'

I hope this solution helps resolve your issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting the click event object data from a dynamically created button with jQuery or JavaScript

I have a task of tracking page button click events. Typically, I track the objects from statically created DOM elements using: $('input[type=button]').each(function () { $(this).bind('click', function () { ...

The troubleshooting issue with jQuery animate Scrolltop malfunctioning

My goal is to use jQuery to scroll the page to a specific div when a button is clicked. Despite not seeing any errors in the JavaScript console, the page does not actually scroll to the desired location. I have tried placing the jQuery js file before and a ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

Issue with Vue.js: routes are not found upon page refresh

Here is a basic vue-routing example: const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/ba ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

What steps should I take to troubleshoot and resolve the connection issue that arises while trying to execute npm install

Following the guidelines from: https://www.electronjs.org/docs/tutorial/first-app I executed commands like mkdir, cd, and npm init. They all ran successfully, generating a file named package.json. Subsequently, I entered npm install --save-dev electron w ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...

When making a jQuery + AJAX request, IE8 is causing a null return value

I'm completely stumped as to why this issue is happening. To start, the code has been checked and validated by the W3C validator as HTML5, except for some URL encoding problems (such as & needing to be &amp;), but I don't have the ability ...

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...

Enhancing date formatting with Angular and Pikaday

I am currently utilizing the angular-pikaday plugin (available at https://github.com/nverba/angular-pikaday) and encountering an issue with date formatting. My objective is to have a model containing a date string formatted as YYYY-MM-dd. To address this ...

Post-render for HTML linkage

Is there a method to execute customized code after Knockout has inserted the html into the DOM and completed rendering? This is required in order to bind a nested view model to dynamically generated html code. Perhaps like this: <div data-bind="html: ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

Show labels for data on a circular graph using angular-chart.js

I recently created a pie chart using angular-chart.js and it's functioning smoothly. However, I'm facing an issue with displaying the data value on each section of the pie chart. My attempt to use Chart.PieceLabel.js by adding the code snippet b ...

Step-by-step guide to implementing a user-friendly search input field using the powerful AngularJS material design framework

I am searching for an effortless method to implement a feature similar to the expandable search text field in angular-mdl. By clicking on a search button, it will expand into a text field. <!-- Expandable Textfield --> <form action="#"> < ...

Senecajs responded with a result that was neither an object nor an array, displaying a Promise

Seeking guidance on incorporating promises into my Seneca modules. Firstly, there is the server.js file that exposes a route: var express = require('express'); var app = express(); var Promise = require('bluebird'); var seneca = requ ...

Is it possible to transfer a JSON object from Silverlight to JavaScript?

Is it possible to pass a JSON object directly from Silverlight to JavaScript, or does it have to be serialized first? ...

What is the best way to showcase the organized values according to their attributes?

How can I sort and display values based on their properties? For example, I want to only show the likes and convert them back into an object so I can use them as properties. I apologize for the previous edit, this is the updated version with a working sim ...