Boosted - Automated Observable with controlled Update alert

Is there a way to create a ComputedObservable in knockout that is computed from non-observable values and manually trigger the Notification?

Answer №1

Essentially, a computed variable functions as a custom event handler for all observables within it.

Whenever an internal observable variable undergoes a change, a notify event is triggered and received by all listeners for further processing.

While the concept may seem straightforward, implementing it on plain JavaScript variables poses challenges. For more insights, check out Listening for variable changes in JavaScript or jQuery.

Should you choose to manually implement this, here are some basic hurdles you might encounter:

  • Variables can be altered at any time and place, necessitating manual notification triggering across the codebase. Missing a trigger could result in inaccurate data.
  • You will also need to set up eventListeners for bindings, such as a total variable requiring computation.
  • Consideration for browser support is crucial. Earlier versions of IE (IE8 and below) do not offer native support for custom events, sometimes requiring workarounds.

My recommendation is to utilize computed (or pureComputed in KO3.2 and above) with observables. This approach streamlines your code significantly. The Knockout framework likely has addressed many of these challenges already, sparing you from reinventing the wheel and maintaining extensive undocumented code.

Included in this post is a Fiddle where I simulate the functionality of the textInput binding for numeric inputs. Notably, different handling methods for IE10, IE9, and pre-IE8 versions as well as special treatment for safari versions below 5 are showcased.

Answer №2

I completely agree with the previous response in suggesting to utilize ko.observable variables within your computed function. It seems unnecessary to use a computed function if its re-evaluation is not automated. In my opinion, it would be more effective to just create a simple function instead.

One potential solution could be to establish a placeholder observable that the computed function depends on. By calling valueHasMutated, you can trigger a re-evaluation:

var a = "A";
var b = "B";

var subscriptionObs = ko.observable();

var ab = ko.pureComputed(function() {
  subscriptionObs();
  return a + b;
});

ko.applyBindings({ab: ab });


b = "C";
subscriptionObs.valueHasMutated();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<p data-bind="text: ab"></p>

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

Flexbox causing issues with relative positioning at the bottom of the screen in various browsers

My flex component looks like this: <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" ... width="100%" height="100%" creationComplete="init()"> ....... <components:Naviga ...

What causes the unexpected behavior of JQuery's .animate() function?

I am currently working on a project that involves creating a div element for the purpose of dragging and dropping files. My goal is to have the height of the div increase when a file is dragged into it, and decrease when the file is dragged out. To achiev ...

How can I differentiate between an unreachable server and a user navigating away in a $.ajax callback function?

Situation: You have a situation where several $.ajax requests to the server are still in progress. All of them end with xhr.status === 0 and xhr.readyState === 0. Possible reasons for this issue: The server might be down (EDIT: meaning it is unreachabl ...

Using jQuery Flot to set a target value and visually indicate its position on the graph

I'm currently using the jquery flot plugin to create graphs. My goal is to mark a specific value on the graph by plotting a horizontal line and displaying its exact value. I have already used markings to draw the line, but I am struggling to figure ou ...

Insert a variable into the URL path of a JavaScript file

Struggling to insert a variable in the code snippet below: eleventyConfig.addPassthroughCopy({ "random-folder/img": "subfolder/img" }); This is what I've attempted: var directory = "random-folder"; eleventyConfig.addPassthroughCopy({ directory + "/ ...

Transferring data between Promises and functions through variable passing

I am facing a challenge. I need to make two separate SOAP calls in order to retrieve two lists of vouchers, and then use these lists to perform some checks and other tasks. I have placed the two calls within different Promise functions because I want to in ...

Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is tri ...

"Utilizing the power of Twitter Bootstrap and Snap.js for

I am currently working on integrating Snap.js by jakiestfu with Twitter Bootstrap. I have managed to make it work to some extent (I can slide the content and open a drawer through a click event). However, I am facing a challenge where the drawer content re ...

The Ajax success function is failing to trigger after receiving a 200 network response

I have a basic HTML page that loads jquery 3.3.1 and an external script file called script.js. I am using a simple node http-server to serve the static page. The data.json file is also in the same folder as the HTML file. However, even though the network c ...

What is the method to retrieve JSON data with data['file.file']?

When trying to query my data using var x = data.file.file;, I encountered an issue where data['file.file'] fails. Is there a way to access this data without having to split the string and walk recursively through it? ...

"Getting Started with Respond.js: A Step-by-Step

I've been struggling to find clear instructions on how to properly set up respond.js. Should I just unzip it into the htdocs folder, or do I only need respond.min.js in there? Then, do I simply reference the file like this... <script src="respon ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...

Trouble with Angular 1.6 ng-repeat not showing search results

I can't seem to figure out why ng-repeat is not showing the search results. Here's what works: Using an HTTP GET request to retrieve all data from the database, and seeing the results displayed by ng-repeat. Sending an HTTP GET request with ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...

Exploring the world of nested routes in Angular and how to efficiently

Hey there! I'm brand new to all of this and still trying to wrap my head around a few things, so any guidance you can offer would be awesome! :) Overview I've got a bunch of projects (/projects) Clicking on a project takes me to a detailed sum ...

Using Python, Scrapy, and Selenium to extract dynamically generated content from websites utilizing JavaScript

I am currently utilizing Python in combination with Selenium and Firefox to extract specific content from a website. The structure of the website's HTML is as follows: <html> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> ...

Steps to initiate my selenium-standalone server: Execute the command "selenium-standalone start"

I'm currently facing a challenge while trying to execute a test script in WebDriverIO. After cloning the code from wdio-cucumber-framework, I am unable to get selenium-standalone to start properly. The error message indicates an issue with geckodriv ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

Adding a MTL texture to an OBJ in your three.js project is a simple process that can enhance

Hello! I am currently working on adding an MTL file to my OBJ in three.js. I had successfully loaded my OBJ and went back to address this issue. However, after adding the code to load the MTL file using MTLLoader, the code seems to be getting stuck at mt ...

Having trouble processing a JSON object using Jquery?

Hello, I am currently working on parsing a JSON object using jQuery. So far, I have successfully extracted all the necessary information from the results except for one crucial piece - the performance tags. Each JSON result is enclosed in an event tag and ...