Connecting Two Knockout Variables Together Without Causing Recursion - javascript

While developing code for a online calculator framework called candy-calc, I have two ko.observables called calcVar1.selUnit and calcVar2.selUnit which I want to connect together. By that I mean, if one changes, the other one will change, and vise versa. The way I have tried to go about this is to create two display variables calcVar1.dispSelUnit and calcVar2.dispSelUnitwhich are ko.computed(). These are bound to in the view, and they have different read/write functions as follows.
// Modified write function
calcVar1.dispSelUnit = ko.computed({
read : function(){
console.log('Reading source var sel unit.');
// Return as usual
return calcVar1.selUnit();
},
write : function(value){
// Write to both of them
console.log('Writing ' + value + 'to both sel unit.');
calcVar1.selUnit(value);
calcVar2.selUnit(value);
},
owner : this
});
// Modified write function
calcVar2.dispSelUnit = ko.computed({
read : function(){
console.log('Reading destination var sel unit.');
// Make it equal to the source variables selected unit
return calcVar2.selUnit();
},
write : function(value){
// Write to both of them
console.log('Writing ' + value + 'to both sel unit.');
calcVar1.selUnit(value);
calcVar2.selUnit(value);
},
owner : this
});
}
So basically, the dispSelUnits are acting as a intermediary to the real selUnit values below, and on write update both selUnit (ko.observables), while on read behave as normal.
I can't see anything wrong with this logic. However, when running this, if I try and update compVar1.dispSelUnit, it enters a infinite loop where compVar1.dispSelUnit gets written then read, and then compVar2.dispSelUnit gets written and read, and then back again.

We also discussed this on Github (https://github.com/mbest/knockout-deferred-updates/issues/17). After looking through his code, I made the following observation and suggestion.
You're getting the recursion problem because the two variables have value bindings to select boxes with different list of units. Although they display the same units, they are actually different objects. The value binding always tries to set the observable to the currently selected item in the list. But because the lists are different, this is really impossible, and the observables switch endlessly between the two values.
To fix this, you need both select boxes to reference the same objects. In standard-resistance-finder.js, do this:
var resistenceUnits = [
new cc.unit('m\u2126', 0.001),
new cc.unit('\u2126', 1.0),
new cc.unit('k\u2126', 1000.0)
];
this.desiredRes = new cc.input(
this,
function() { return true; },
resistenceUnits,
0);
...
this.actualRes = new cc.output(
this,
...
resistenceUnits,
0, 2);
Regarding the question of keeping two observables in sync, this question might provide some answers: Simple, clean way to sync observables from different view models

Related

Filtering smart-table on transformed data

Apologies in advance, I am not a very experienced JS programmer, and even less so with AngularJS, but am trying to make some improvements on a legacy codebase that is using Angular 1.5.9 and Smart Table to display information from a database.
I've read all about st-search and st-safe-src vs. st-table, etc., but I am having trouble filtering on my table, since there are transformations happening on the underlying data before it gets displayed. The ng-repeat variable in my case is transaction, which has various fields to hold information for that transaction, such as payee, which holds a UUID pointing to another database document. In the app, we display the name of that payee using a function from another controller (dbCtrl.getPayeeName()), but the underlying data is the UUID. Thus, when attempting to filter with Smart Table, it does not filter on the displayed names, and only works when entering the UUID into the filter field.
A small example (with lots of the intervening bits removed, but hopefully enough to demonstrate my confusion):
<div class="account"
st-table="displayedTransactions"
st-safe-src="transactions"
disable-ng-animate>
...
<div><input st-search="payee" placeholder="search for payee" class="input-sm form-control" type="search"/></div>
...
<div ng-repeat="transaction in displayedTransactions track by transaction.id">
...
<div class="account__td" transaction-field-focus-name="payee">
{{dbCtrl.getPayeeName(transaction.payee)}}
</div>
...
</div>
Is there a relatively simple way to get the filtering to work for a situation like this where the displayed data is different than the underlying data? From what I'm reading in the documentation, it sounds like this might require some sort of custom plugin, which sounds like more work, but I could maybe figure out. I just wanted to see if I'm missing something obvious before heading down that route.
Circling back on this, I was able to accomplish what I needed using the st-set-filter attribute as described in the Strict mode filtering section of the documentation, as well as this helpful answer from laurent back in 2014.
Essentially, I added st-set-filter="transactionFilters" to my table in my html template, as well as input tags with st-search="prop_to_search" attributes. Then in my applications module (I put this in one of the controllers, not sure if that's totally correct) I defined a filter such as below. expression gets passed into this code as an object with string values for whatever you typed in, so if you had three search fields, you'd get an object like:
{
"prop_to_search1": "value1",
"prop_to_search2": "value2",
"prop_to_search3": "value3"
}
In the filter function, I wrote an if block for each property that could come in, and then do my custom transformations and pattern matching there. This way, I have full control over the eventual matching, and rather than searching on the UUID, I can do something like $rootScope.dbCtrl.getPayeeName(uuidToSearch) instead. This is all acceptably performant in my use case, but I could probably cache those database lookups as a potential optimization.
angular.module('myApp').filter('transactionFilters', function($rootScope, $filter){
return function(array, expression){
// console.log(`expression is: ${JSON.stringify(expression, null, 4)}`)
return array.filter(function(val, index){
// in this function's context, `expression` is an object with
// the active filters entered in each field; `val` is the data
// representation of each row of the table
// if this function returns true, the row will match and smart-table
// will show it, otherwise it will be hidden
// define matches all at once, check them all, then return
// a big logical AND on all of them
let accountMatch = true;
let payeeMatch = true;
let categoryMatch = true;
if (expression.account) {
uuidToSearch = val.account // this is the account UUID
strToSearch = $rootScope.dbCtrl.getAccountName(uuidToSearch).toLowerCase(); // convert to an account name (we could memoize this to improve performance)
if (strToSearch) {
// if the account had a name (it always should, but catch in case)
// then check if the row's account contains the text entered in the filter field
accountMatch = strToSearch.includes(expression.account.toLowerCase());
} else {
accountMatch = false;
}
}
if (expression.payee){
if (val.payee) {
uuidToSearch = val.payee
strToSearch = $rootScope.dbCtrl.getPayeeName(uuidToSearch).toLowerCase();
}
if (strToSearch) {
payeeMatch = strToSearch.includes(expression.payee.toLowerCase());
} else {
payeeMatch = false;
}
}
if (expression.category) {
if (val.category) {
strToSearch = $rootScope.dbCtrl.getCategoryName(val.category, val.date).toLowerCase()
categoryMatch = strToSearch.includes(expression.category.toLowerCase())
} else {
categoryMatch = false;
}
}
return (
accountMatch &&
payeeMatch &&
categoryMatch
)
})
}
});

Page Object Pattern asynchronous using node.js selenium

I am having a hard time trying to adjust to asynchronous using node.js. I ran into an issue when using selenium-webdriver and the page object pattern. I feel like somethings have to be synchronous when doing automation testing or your tests will fail because you clicked a button before inserting data. I am having an issue similar to this. I want to add an employee and then search for the employee, but the search for employee is performing before add employee.
var employee = new Employee('grimlek', 'Charles', 'Sexton', 'TitleTitle',
'Upper Management', 'Company Admin', 'Contractor', '-7', 'Remote',
'05212016', '3369407787', '3368791234', 'charles#example.com',
'charles.sexton', 'Skype', 'abcdefgh');
driver.get('https://website.com/login')
.then(function() {
//This behaves as intended
loginPage.login('company.admin', 'password') })
.then(function() {
//Add employee
employeePage.addEmployee(employee) })
.then(function() {
//Search for employee after employee is added
employeePage.searchEmployee(employee)});
EmployeePage Object
var EmployeePage = function (driver) {
this.addEmployee = function (employee) {
driver.findElement(webdriver.By.css('button[class=\'btn btn-default\']')).then(function (element) {
//
//Search employee function is done before the line below this
//
element.click();
}).then(function () {
setTimeout(function () {
driver.findElement(webdriver.By.id('employee_username')).then(function (element) {
element.sendKeys(employee.username);
});
driver.findElement(webdriver.By.id('employee_first_name')).then(function (element) {
element.sendKeys(employee.firstName);
});
driver.findElement(webdriver.By.id('employee_last_name')).then(function (element) {
element.sendKeys(employee.lastName);
});
driver.findElement(webdriver.By.id('employee_title_id')).then(function (element) {
element.sendKeys(employee.title);
});
driver.findElement(webdriver.By.id('employee_role')).then(function (element) {
element.sendKeys(employee.role);
});
}, 5000);
});
//
//
//Search employee should occur when the thread leaves the function
//
};
this.searchEmployee = function (employee) {
driver.findElement(webdriver.By.css('input[class=\'form-control ng-pristine ng-valid\']')).then(function(element) {
element.sendKeys(employee.firstName + ' ' + employee.lastName);
});
};
};
module.exports = EmployeePage;
I know that both searchEmployee and addEmployee functions don't return a promise and I am trying to chain them with the .then function. I do believe this is sorta my problem but I need help with how it should be done and not how I can rig it. Should I use callbacks? I have worked on this problem for going on four hours now and I have tried googling and doing research on various topics. If I didn't provide enough code please let me know and I will provide a simplified runnable example.
A laudable goal is to make each test independent. If a change is made to the application (e,g, bug fix) only the impacted test(s) need to be executed. Also, it makes moving to grid thinkable.
But this is difficult to achieve in practice. Your test has to include all tests needed to satisfy the prerequisites.
Cucumber has feature files that include scenarios Each scenario is a test. Scenarios are executed in the order they are listed in the feature file. So one way to organize things is to include all the prerequisite scenarios before your test in a feature file, You can add tag(s) before the Feature statement so that when you execute that tag the entire feature file runs. Perhaps the first scenario resets (a subset of) the database to a know state.
The trick would be to run features in parallel on multiple machines. If you point those multiple clients to the same server beware that the features should not create or update overlapping entities that could collide when written to the database by the server. E.g. "What do you mean that user 'tom' already exists?" Each feature needs to create a unique user name.
The way of approach using cucumber is to divide you steps for every individual operation.
Ex:
Given I am on XYZ Form
And I provide all form details
In above case, for step And I provide all form details you will be including all the fields in step definition and start filling the fields say name, last name, address in single step definition.
Instead of this we should divide the step for every individual field like:
Given I am on XYZ Form
And I provide name details in XYZ Form
And I provide last name details in XYZ Form
And I provide address details in XYZ Form
And then we will be writing 3 step definition which of course will be running sequentially.
You may feel that the typing work got increased and step definitions got increased unnecessarily, but this will actually help you when a field gets removed from the application itself, you will be only needing to delete related step from future file.
More over you can easily test validation for fields by just commenting one of the step in your feature file.
And your code will be more easy to maintain as every steps is working independently.
And of course sequential work will get achieved.

Programmatically insert variables into Meteor Templates with Blaze.render + Blaze.view or Blaze.with

I'm trying to figure out how to programmatically insert a variable helper into a template using the Blaze API. I believe it needs to be done using some form of:
Blaze.render(Blaze.with('variable', contentFunction);
However, I'm struggling to get the contentFunction to work properly. I tried a function that returns a Session variable:
var session_var = function() {
return Session.get('myVariable');
};
However, I keep getting undefined errors. I know this could be done if I defined a separate template to be rendered, but that seems a bit much for this particular case. I was wondering if someone could explain how Blaze.with and Blaze.view work. Also, is it possible to programmatically insert just a variable helper into a template?
Without knowing exactly what you're trying to do, it's not clear if this is the easiest way of going about things.
However, if you look at the docs, you'll see that you can either supply the session variable in a data context and use Blaze.With, or supply no data context and use Blaze.View instead (which appears to be what you're going for).
So, if you want to render a reactive data context, it has to be supplied in the first argument to Blaze.With. Try something like this:
var myView = Blaze.With(
function() {
return {
foo: Session.get('foo')
};
},
function() {
return Spacebars.mustache([
'the value of foo is ',
this.lookup('foo')
]);
}
);
Blaze.render(myView, document.body); // or whatever element you want to render it inside
Alternatively, for Blaze.View:
var myView = Blaze.View(
function() {
return 'the value of foo is ' + Session.get('foo');
}
);
Blaze.render(myView, document.body);
To be honest, the easiest way to learn about the structure of renderable content (which is the difficult bit if you're doing this programmatically) is to study the stuff that the Spacebars compiler churns out. In other words, find an interesting template/sub-template that's been generated from quasi-HTML, pick an element out of it and run Blaze.getView([ELEMENT])._render, then study the result.

link 2 javascript objects

I am working on an angularJS app and i found a problem that I cant solve. I have a variable with predefined text that I want to replace in an email with the actual values, it looks like this:
$scope.predefinedVars = {
'client_name': $scope.itemPartner.name,
'client_city': $scope.itemPartner.city,
'client_county': $scope.itemPartner.county,
'client_address': $scope.itemPartner.address,
'client_phone': $scope.itemPartner.phone,
'client_email': $scope.itemPartner.email
};
and so on...
Now later on, when I choose a partner, the itemPartner object changes the data. For example: i have a function to watch when I change the partner from a select box:
$scope.$watch('newContract.partner_id', function() {
$scope.itemPartner = _.where($scope.listPartners, {'id': $scope.newContract.partner_id})[0];
alert(JSON.stringify($scope.itemPartner));
});
Now, in the alert, I can see the itemPartner data has changed, but if I try to read the values from my 1st variable $scope.predefinedVars, the values are still empty and do not change.
Is there a way to force the values to change when I change the itemPartner object ?
The problem is that you have set the fields of your predefinedVars object to a primitive. In javascript, primitives are passed by value, not by reference (google if you're not sure what that means).
The result is that any reference to the object you used to set it originally is lost.
You have a couple of alternatives:
Instead of replacing the email using the data from $scope.predefinedVars, use the data from $scope.itemPartner. This is less work.
create a function that repopulates predefinedVars
e.g.
function populatePredefinedVars (partner){
$scope.predefinedVars = {
'client_name': partner.name,
'client_city': partner.city,
'client_county': partner.county,
'client_address': partner.address,
'client_phone': partner.phone,
'client_email': partner.email
};
}
$scope.$watch('newContract.partner_id', function() {
$scope.itemPartner = _.where($scope.listPartners, {'id': $scope.newContract.partner_id})[0];
populatePredefinedVars($scope.itemPartner);
});

How to create a well formed global javascript object containing special functions

I am creating a small project that heavily relies on JavaScript. I come from php/mysql and now stepping into node.js/javascript/mongodb, and I hve to say it's quite a mindswitch.
I want to create a simple object that has some special function that I can use in the page. I have been looking at some tutorial, and looking at the libraries such as jquery and backbone, but I need some final advice on my decision.
I only need some small functions, and no cross-browser support, that's why I don't choose something like backbone. Maybe ill change to that later when I have a better crasp on JavaScript programming.
What is confusing me is whether to use the new, or maybe wrapping the code into a self-invoking function.
I see jquery creates an object inside the window and than exposes that, but I have no idea how that works.
Enough intro, now to the point. I have created something like this:
var $s = Object.create({
page: Object.create({
title: 'pagetitle',
html: '',
data: {},
render: function(){
// Basic render function
}
}),
socket: Object.create({
// My websocket connection
}),
store: function(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
retrieve: function(key) {
var value = localStorage.getItem(key);
return value && JSON.parse(value);
},
slugify: function(slug){
return slug.replace(/[^a-zA-Z 0-9-]+/g,'').toLowerCase().replace(/ /g,'-');
}
});
This are just a few random functions I put in.
I haven't tested this yet, it is a draft, I want to know if this is any good.
Now I was thinking i can do some stuff like this:
$s.page.html = 'somehtml';
$s.page.render();
// Maybe
$s.store( $s.page.title, $s.page.html );
I do use jQuery and jQuery templating, so something like this could be possible:
$.tmpl( $s.page.html, $s.page.data ).appendTo( "#content" );
Nothing fancy is needed here. You can create a global javascript object with a method like this:
var myGlobalObject = {};
myGlobalObject.testFunction = function() {
// put your code here
};
You can then call that like this:
myGlobalObject.testFunction();
One slightly more flexible design pattern you will often seen used is this:
var myGlobalObject = myGlobalObject || {};
myGlobalObject.testFunction = function() {
// put your code here
};
This is used when there might be lots of different pieces of code contributing to myGlobalObject and they all want to make sure that it's properly declared before adding properties to it. This way of doing it, creates it if it doesn't already exist and if it does already exist, leaves the methods and properties on it that might already be there. This allows multiple modules to each contribute initialization to myGlobalObject without regards for the order they load.

Categories

Resources