What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decrement situations in the data stream. However, my scenario requires values to be subtracted when edited, making the .scan approach unsuitable or possibly incorrectly implemented.

HTML Structure:

<ul style="repeat-direction: vertical; list-style-type: none;">
  <li><input data-group="0"></li>
  <li><input data-group="0"></li>
  <li><input data-group="0"></li>
</ul>
<ul style="repeat-direction: vertical; list-style-type: none;">
  <li><input data-group="1"></li>
  <li><input data-group="1"></li>
  <li><input data-group="1"></li>
</ul>

The current workaround involves iterating through the inputs upon receiving a throttled keyup event, then updating a span whenever there is a change.

groupZeroEvents = events.filter (val) ->
   Math.floor(val[0]) == 0 # identifies the group associated with the input

groupZeroEvents.onValue (val) ->
    sum = 0
    $("input[data-group='0']").each (i,el) ->
      sum += Math.floor($(el).val())
    $('span#sum-g0').html(sum)

This solution gets the job done, but it seems inefficient. It appears like there must be a more effective way to leverage Bacon.js.

Answer №1

The total will vary depending on the current values of several inputs. If you define these inputs as Properties, you can arrive at a more elegant solution:

function calculateTotal(numbers) { return _.reduce(numbers, (function(x,y) {return x + y}), 0); }

// array of Properties representing the value of each group-zero-element
var groupZeroValues = $("input[data-group=0]").map(function(index, elem) {
     return $(elem).asEventStream("keyup")
            .map(function(e) { return parseInt($(e.target).val()); })
            .toProperty(0)
     }).toArray();

// calculating the sum Property
var groupZeroSum = Bacon.combineAsArray(groupZeroValues).map(calculateTotal)

// setting the calculated value to the "text" method of the sum element
groupZeroSum.assign($("#sum-g0"), "text")

I haven't had a chance to test this in action yet, but I am confident that the concept is sound.

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

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

The React context is currently yielding an undefined value

I am puzzled by this issue. I have double-checked to ensure that the states value is not undefined, and it isn't. However, I am unable to pinpoint where I may be making a mistake. Here is my authContext.js file: const initialState = { isAuthorized: ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

Encountering an Issue with Dynamic Imports in Cypress Tests Using Typescript: Error Loading Chunk 1

I've been experimenting with dynamic imports in my Cypress tests, for example using inputModule = await import('../../__tests__/testCases/baseInput'); However, I encountered an issue with the following error message: ChunkLoadError: Loading ...

Obtain identical encryption results with CryptoJS (JavaScript) and OpenSSL (PHP)

I am in the process of integrating a PHP encryption function into a ReactJS application. I have a requirement to transmit the token in a specific format that was generated using the OpenSSL library function (openssl_encrypt). It has been observed that the ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

Adjusting the React Material UI TextField behavior upon a change in value while maintaining the

I have an MUI TextField component that I would like to trigger a function when it changes, while still allowing it to function as usual (without being a controlled input). <TextField onChange={(e)=>{ doSomething(e.target.value) //perhaps call ...

What are the benefits of incorporating a mock AJAX call in testing scenarios?

I recently came across a tutorial on TDD React here and I'm having trouble understanding the following test scenario: it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => { nock('https://api. ...

What is the correct method for notifying the progress of time using jQuery?

I'm looking for a way to display the processing time of my PHP code using jQuery Here's an example of my PHP code : <?php //some queries to database ?> Below is my jQuery code: $.ajax({ type: "POST", url: "action. ...

Retrieve mongodb objects that fall within a specified date range

Within my collection, there is an example document structured as follows: { "_id" : ObjectId("5bbb299f06229dddbaab553b"), "phone" : "+38 (031) 231-23-21", "date_call" : "2018-10-08", "adress_delivery" : "1", "quantity_concrete" : "1", ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

create new Exception( "Invalid syntax, expression not recognized: " msg );

Can someone assist me in identifying the issue at hand? Error: There seems to be a syntax error, and the expression #save_property_#{result.id} is unrecognized. throw new Error( "Syntax error, unrecognized expression: " msg ); Here is the c ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Next.js version 14 is having difficulties displaying the loading.tsx file

click here for image description Why is the loading not displaying when navigating to /profile? How can I fix this issue? export default function Loading() { // You can add any UI inside Loading, including a Skeleton. return ( <div> lo ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...