Utilizing RxJs in JavaScript: How to use bindNodeCallback on an Object method that accepts input parameters

Imagine having a class like this:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/bindNodeCallback';

export class MyClass {
    name: string;

    doSomethingWithName(cb: (err) => void) {
        const error = 'I have no name';
        const success = 'My name is: ' + this.name;
        if (!this.name) {
            return cb(error)
        }
        return cb(success);
    }

    doSomethingWithNameAndParam(param: string, cb: (err) => void) {
        const error = 'I have no name and param value is: ' + param;
        const success = 'My name is: ' + this.name + ' and my param value is :' + param;
        if (!this.name) {
            return cb(error)
        }
        return cb(success);
    }

}

MyClass has methods that require a callback as the last parameter.

The goal is to utilize the bindNodeCallback method of rxjs.Observable to generate an Observable for each method instead of using callbacks.

The first method works correctly without any issues. Below is the code snippet that creates an Observable:

export function myClassObjFunctionObs(myObj: MyClass): Observable<MyClass> {
    return Observable.bindNodeCallback(myObj.doSomethingWithName).call(myObj);
}

Here's how you can use the above Observable:

import {MyClass} from './my-class';
import {myClassObjFunctionObs} from './my-class';

const myClass = new MyClass();
myClass.name = 'I am your class';

myClassObjFunctionObs(myClass)
.subscribe(
    data => console.log('data', data),
    err => console.error(err),
    () => console.log('DONE')
)

The challenge lies in creating a similar solution for the method doSomethingWithNameAndParam, which requires a parameter before the callback.

Please provide any assistance or guidance on achieving this task.

Answer №1

Below is a straightforward and clear method to bind the parameter:

export function myClassObjFunctionObs(myObj: MyClass): Observable<MyClass> {
    return Observable.bindNodeCallback(myObj.doSomethingWithNameAndParam.bind(myObj, 'TEST PARAM')).call(myObj);
}

You may also want to consider converting your doSomethingWithNameAndParam function into a wrapper that curries the parameter and returns a doSomething function:

doSomethingWithNameAndParam(param: string) {
    return (cb: (err) => void) => {
      const error = 'I have no name and the parameter value is: ' + param;
      const success = 'My name is: ' + this.name + ' and my parameter value is :' + param;
      if (!this.name) {
          return cb(error)
      }
      return cb(success);
    }
}

Then you can use it simply like this:

export function myClassObjFunctionObs(myObj: MyClass): Observable<MyClass> {
    return Observable.bindNodeCallback(myObj.doSomethingWithNameAndParam('TEST PARAM')).call(myObj);
}

Check out the stackblitz example here: https://stackblitz.com/edit/angular-za2y2k

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

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

Transforming jQuery code to pure vanilla Javascript

For my project, I decided to convert my jQuery code into native JavaScript. The goal is to eliminate the dependency on jQuery and achieve the same functionality. The current setup involves two pages - page.html and side.html. The page.html document fetches ...

"Radio button is set as default option, however the dropdown menu is not displaying

I am experiencing an issue with a credit card payment form on my website. Unlike similar websites where the dropdown list of credit cards automatically displays when the page loads, on this site the list does not show until a second click occurs on the alr ...

What is the fastest way to emulate CSS3 box radius for IE in terms of rendering speed?

There are numerous options available in JavaScript, .htc, and jQuery to create rounded corners for IE 6,7,8. (Not compatible with IE 8) http://code.google.com/p/jquerycurvycorners/ http://code.google.com/p/curvycorners/ Which solution offers the faste ...

Ways to incorporate unique fonts into a Next.js application residing under a subdirectory of a domain

Currently, I have a Next.js application deployed on a sub-path of a domain (for example example.com/my-next-js-app). To handle bundle scripts and styles, I utilized the Next.js configuration like so: const isProd = process.env.NODE_ENV === 'production ...

Issues related to React hooks when using media queries

I've been working on a react hook that verifies if the user is using a browser with reduced motion capabilities, but I'm running into an issue where the window object remains undefined. So far, this is what my code looks like: import { useEffect, ...

Issue: Unable to locate module ' Stack trace: - /var/runtime/index.mjs when running Lambda function generated using Terraform and Node.js version 18 or higher

My Terraform setup involves a Lambda function with a Node.js version of >= 18, following the steps outlined in this helpful article. However, upon attempting to invoke the Lambda function, CloudWatch throws the following error: "errorType" ...

What is the proper way to retrieve items from an Array that have an index that is evenly divisible by

let numbers = [4, 5, 7, 8, 14, 45, 76]; function getEvenElements(arr) { let evenArray = []; for (let i = 0; i < arr.length / 2; i++) { evenArray.push(arr[2 * i]); } return evenArray.filter(num => num !== undefined); } alert(getEvenEle ...

When integrating AngularJS with CKEditor, an error regarding module dependency injection may occur, causing the following message to be displayed:

Just starting out with Angularjs and attempting to integrate Ckeditor into my webapp. Currently encountering the following error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=editor&p1=Error%3A%…Flo ...

Using the Play framework to showcase data in an HTML table

I have a project where I am working with multiple tables, one of which is a Person table containing id and name attributes. I have successfully retrieved the data from the database using MySql and converted it into JSON. However, I am struggling to find a ...

Nested List in Vuetify Components

I am struggling to create a deeply nested list with more than three levels in Vue.js. When I attempt to nest children items inside a child item using v-list, nothing is displayed. Is it even feasible to have such a complex nested list structure in Vuetify ...

What location is the optimal choice for documenting logs at a debugging level?

My team and I have been deeply contemplating the best location for writing a debug-level log during our development process. We are utilizing winston in conjunction with winston-daily-rotate-file to separate out different aspects of logging, as well as ne ...

Altering the way in which URL parameters are attached to links depending on the destination

Our company utilizes Unbounce to create PPC landing pages on a subdomain, which then direct users back to our main website. We have implemented code that appends the AdWords gclid variable to outgoing links: $(document).ready(function() {var params = win ...

Documentation in TypeScript with JSDoc and using the new Rest type syntax

Encountering an issue while integrating TypeScript into a large existing React/Redux application. To test things out, I decided to convert one of my React files to a .ts file. My approach involves using JSDoc to add types to the imported JS files in order ...

Removing duplicate values in Vue after sorting

Explore <div v-for="todo in sortedArray"> <b-button block pill variant="outline-info" id="fetchButtonGap" v-model:value="todo.items[0].arrivalTime"> {{fromMilTime(todo.items[0].arrivalTime)}} < ...

Updating the current date at midnight or on the new day in JavaScript can be achieved using specific date and time

I have a web watch that is supposed to work 24/7 and display the digital time along with the current day. However, my issue is that when the time passes midnight, the current day does not update and I am forced to restart the entire application. I attempt ...

The 'onChange' event in React is being triggered only once

Currently utilizing material-ui Library Below is my React component: import Checkbox from '@material-ui/core/Checkbox'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import React from "react"; import { withStyles ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

Unexpected symbol in JSON parsing with JavaScript

let information; $.ajax({ url: link, type: 'POST', dataType: "json", success: function (data, textStatus) { information = data; alert(data.name); } }); I am attempting to retrieve JSON-encoded data from a spe ...

Utilizing single-use bindings for a unique element directive

I'm working on a new directive called <call-card> and I want to implement one-time bindings as an exercise for optimizing future directives. Here is the definition object for this directive: { restrict: 'E', controllerAs: &ap ...