Rx timer state not updating in view in Cycle.js - javascript

I'm starting a timer when someone clicks a button that I intend to use as the opacity for some element. When I use do to trace the value I can see it spitting out to the console 40 times, but in the view the number stays put. Not sure where I'm going wrong here:
let intent = ({ DOM }) => ({
clickLogin$: DOM.select('.sign-in').events('click').map(ev => true)
})
let model = ({ clickLogin$ }) =>
Rx.Observable.combineLatest(
clickLogin$.startWith(false),
clickLogin$.map(x =>
Rx.Observable.timer(1, 1)
).switch().startWith(0).take(40),
(signingIn, fadeValue) => ({ signingIn, fadeValue })
)
let view = (state$) => {
return state$.do(
x => console.log(x.fadeValue)) // this fires |--1-2-3-4-5-6-7-8-->
.map(({ signingIn, fadeValue }) =>
div(`.app`, [
div([fadeValue]), // this value does not change
If(signingIn,
div(`.overlay`, {
style: {
backgroundColor: `rgba(0, 0, 0, 0.${fadeValue})` // nor does this
}
})
)
])
)
}
let main = (sources) => {
let view$ = view(model(intent(sources)))
return {
DOM: view$,
history: sources.History,
Props: sources.Props,
}
}
UPDATE: Turns out having a small error in hyperscript caused it strange behaviour. I didn't even include it in my example because I didn't think it was relevant.
div(`content`, [ `testing` ])
Simply changing the above to (adding indication of class)
div(`.content`, [ `testing` ])
Caused everything to magically work.

This is probably not a full answer, but it helps identifying the problem. I removed the If part of the view code generation, and added repeat, put that in tricycle and you can see that the fadeValue is generated sequentially as expected.
var Cycle = require('#cycle/core');
var CycleDOM = require('#cycle/dom');
var Rx = require('rx');
var makeDOMDriver = CycleDOM.makeDOMDriver;
var div = CycleDOM.div;
var sources = {
DOM: makeDOMDriver('.app')
};
let main = (sources) => {
let intent = ({ DOM }) => ({
clickLogin$: Rx.Observable.interval(3000).take(5).share()
})
let model = ({ clickLogin$ }) =>
Rx.Observable.combineLatest(
clickLogin$.startWith(false),
clickLogin$.flatMapLatest(function (x) {
return Rx.Observable.timer(200, 200);
}).take(10).repeat(),
(signingIn, fadeValue) => ({ signingIn, fadeValue })
)
let view = (state$) => {
return state$.do(
x => console.log(x.fadeValue)) // this fires |--1-2-3-4-5-6-7-8-->
.map(({ signingIn, fadeValue }) =>
div(`.app`, [
div([fadeValue]) // this value does not change
])
)
}
let view$ = view(model(intent(sources)))
return {
DOM: view$,
history: sources.History,
Props: sources.Props,
}
}

Related

How to write JavaScript code that allows for defaults to be overrided

I would like to use this text-highlighting library in my Vue project. Here's an example from their website of how it can be used:
import TextHighlighter from '#perlego/text-highlighter';
import { isDuplicate } from './utils';
import highlightsApi from './services/highlights-api';
class ArticleView {
constructor(data) {
this.data = data;
const pageElement = document.getElementById("article");
this.highlighter = new TextHighlighter(
pageElement,
{
version: "independencia",
onBeforeHighlight: this.onBeforeHighlight,
onAfterHighlight: this.onAfterHighlight,
preprocessDescriptors: this.preprocessDescriptors,
onRemoveHighlight: this.onRemoveHighlight
});
}
onBeforeHighlight = (range) => {
return !isDuplicate(range)
}
onRemoveHighlight = (highlightElement) => {
const proceed = window.confirm("Are you sure you want to remove this highlight?");
return proceed;
}
preprocessDescriptors = (range, descriptors, timestamp) => {
// Add an ID to the class list to identify each highlight
// (A highlight can be represented by a group of elements in the DOM).
const uniqueId = `hlt-${Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)}`;
const descriptorsWithIds = descriptors.map(descriptor => {
const [wrapper, ...rest] = descriptor;
return [
wrapper.replace(
'class="highlighted"',
`class="highlighted ${uniqueId}"`
),
...rest
];
});
return { descriptors: descriptorsWithIds, meta: { id: uniqueId } };
}
onAfterHighlight = (range, descriptors, timestamp, meta) => {
highlightsApi.saveBatch(meta.id, descriptorsWithIds)
.then((result) => {
// Do something with the highlights that have been saved.
})
.catch((err) => console.error(err));
}
render = () => {
// Code that takes the data for the article and adds it to the DOM
// based on a html template here.
}
}
Using the above example, I would like to setup the highlighter (similar to the above code, but in a different file, for example ./utils/highlighter.js) with all the default options I want (onBeforeHighlight, onRemoveHighlight, etc.), and then be able to import it from there and override the options for which I don't want to use the defaults, so it looks something like this in the importing file:
import highlighter from "../utils/highlighter.js";
const overridingOptions = {
onAfterHighlight: (range, descriptors, timestamp, meta) => {
console.log(range, descriptors, timestamp, meta);
}
};
const target = document.getElementsByClassName("testme")[0];
highlighter(target, overridingOptions);
For some reason, I am not able to understand how to modify the ArticleView example to fit my needs, so I think I need to see this done once. How should the code in ./utils/highlighter.js look to make this possible?

How to use behaviorSubject when removing item from array

I have angular 8 application.
And I have two components, like child - parent relationship. So I remove the item from the child, but then the item is still visible in the parent(list of items). Only after page refresh the item is gone from the list.
So I have this service:
export class ItemListService {
_updateItemChanged = new Subject<any>();
_removeItemChanged = new BehaviorSubject<any>([]);
constructor() {}
}
and this is item.ts - child:
openRemoveDialog() {
const dialogRef = this.dialog.open(ItemRemoveDialogComponent, {
width: '500px',
height: '500px',
data: {
dossierId: this.dossier.id,
item: this.item,
attachments: this.item.attachments
}
});
this.itemListService._removeItemChanged.next(this.item.title);
dialogRef.afterClosed().subscribe(result => {
if (result === true) {
this.router.navigate(['/dossier', this.dossier.id]);
}
});
}
and this is the view.ts(item list) - parent: so in this component the refresh has to be made
ngOnInit(): void {
this.show = !this.router.url.includes('/item/');
this.itemlistService._updateItemChanged.subscribe(data => {
const index = this.dossierItems.findIndex(a => a.id === data.id);
this.dossierItems[index] = data;
});
this.itemlistService._removeItemChanged.subscribe(data => {
// this.dossierItems.pop(); What I have to fill in here?
});
So what I have to change?
Thank you
and this is the remove function:
remove() {
this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
.subscribe(() => {
this.dialogRef.close(true);
}, (error) => {
const processedErrors = this.errorProcessor.process(error);
this.globalErrors = processedErrors.getGlobalValidationErrors();
});
}
I have it now like this:
remove() {
this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
.subscribe(() => {
this.dialogRef.close(true);
this.itemListService._removeItemChanged.next(true);
}, (error) => {
const processedErrors = this.errorProcessor.process(error);
this.globalErrors = processedErrors.getGlobalValidationErrors();
});
}
and in the view.ts, like ths:
ngOnInit(): void {
this.itemlistService._removeItemChanged.subscribe(update => update === true ? this.dossierItems : '');
}
but still the list will not be refreshed
You need to create a new reference to your array for Angular to update the screen like this
this.itemlistService._removeItemChanged.subscribe(data => {
// this.dossierItems.pop(); What I have to fill in here?
this.dossierItems = this.dossierItems.filter(e => e.title !== data);
});

unable to select all checkboxes in tree using angular2-tree on init

Objective : i have a button named "feed data" so when ever i click it the data will be loaded i mean the tree with checkboxes here my requirement is when ever i click it along with data all the check boxes have to be checked on init i tried using
this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true));
but it is not working below is my code
click(tree: TreeModel) {
this.arrayData = [];
let result: any = {};
let rs = [];
console.log(tree.selectedLeafNodeIds);
Object.keys(tree.selectedLeafNodeIds).forEach(x => {
let node: TreeNode = tree.getNodeById(x);
// console.log(node);
if (node.isSelected) {
if (node.parent.data.name) //if the node has parent
{
rs.push(node.parent.data.name + '.' + node.data.name);
if (!result[node.parent.data.name]) //If the parent is not in the object
result[node.parent.data.name] = {} //create
result[node.parent.data.name][node.data.name] = true;
}
else {
if (!result[node.data.name]) //If the node is not in the object
result[node.data.name] = {} //create
rs.push(node.data.name);
}
}
})
this.arrayData = rs;
tree.selectedLeafNodeIds = {};
}
selectAllNodes() {
this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true));
// firstNode.setIsSelected(true);
}
onTreeLoad(){
console.log('tree');
}
feedData() {
const results = Object.keys(this.data.info).map(k => ({
name: k,
children: this.data.info[k].properties
? Object.keys(this.data.info[k].properties).map(kk => ({ name: kk }))
: []
}));
this.nodes = results;
}
feedAnother() {
const results = Object.keys(this.dataa.info).map(k => ({
name: k,
children: this.dataa.info[k].properties
? Object.keys(this.dataa.info[k].properties).map(kk => ({ name: kk }))
: []
}));
this.nodes = results;
}
onActivate(event) {
this.selectedDataList.push(event.node.data);
console.log(this.selectedDataList)
}
onDeactivate(event) {
const index = this.selectedDataList.indexOf(event.node.data);
this.selectedDataList.splice(index, 1);
console.log(this.selectedDataList)
}
below is my stackblitz https://stackblitz.com/edit/angular-hrbppy
Use updatedata and initialized event to update the tree view to check all checkboxes.
app.component.html
<tree-root #tree *ngIf ="nodes" [nodes]="nodes" [options]="options" [focused]="true"
(initialized)="onTreeLoad()"
(updateData)="updateData()"
(select)="onActivate($event)"
(deselect)="onDeactivate($event)">
</tree-root>
It'll initiate tree-root component only if nodes variable is available,
then in the initialized and updateData event call selectAllNodes method to select all checkboxes.
app.component.ts
updateData() {
this.selectAllNodes();
}
onTreeLoad(){
this.selectAllNodes();
}
Refer to this slackblitz for working example.
just, in your function feed data call to your function this.selectAllNodes() enclosed in a setTimeout. You can see your forked stackblitz
setTimeout(()=>{
this.selectAllNodes()
})
NOTE: I see in your code you try to control in diferents ways the items selected. I simplified using a recursive function.
In this.treeComp.treeModel.selectedLeafNodeIds we have the items that are changed, so
getAllChecked()
{
const itemsChecked=this.getData(
this.treeComp.treeModel.selectedLeafNodeIds,null)
console.log(itemsChecked);
}
getData(nodesChanged,nodes) {
nodes=nodes||this.treeComp.treeModel.nodes
let data: any[] = []
nodes.forEach((node: any) => {
//in nodesChanged we has object like {1200002:true,123132321:false...}
if (nodesChanged[node.id]) //can be not changed, and then it's null because
//it's not in object or can be changed to false
data.push({id:node.id,name:node.name})
//or data.push(node.name); //if only need the "name"
if (node.children)
data=[...data,...this.getData(nodesChanged,node.children)]
}
);
return data
}
Updated I updated the function getData to include the "parent" of the node, but looking the code of #Raghul selvam, his function like me more than mine.
getData(nodesChanged,nodes,prefix) {
nodes=nodes||this.treeComp.treeModel.nodes
let data: any[] = []
nodes.forEach((node: any) => {
if (nodesChanged[node.id])
data.push(prefix?prefix+"."+node.name:node.name)
if (node.children)
data=[...data,...this.getData(nodesChanged,node.children,prefix?prefix+"."+node.name:node.name)]
}
);
return data
}
And call it as
this.getData(this.treeComp.treeModel.selectedLeafNodeIds,null,"")
You could add this in your onTreeLoad function. You could add a boolean flag(treeLoaded) for tracking if the tree has loaded or not.
onTreeLoad(tree){
this.selectAllNodes();
this.treeLoaded = true;
}

Variable is pushed, but it doesn't exist later

I have the following code:
const scenarioList = []
const randomScenario = () => {
return scenarioList[Math.floor(Math.random() * scenarioList.length--)]
}
class Scenario{
setBG(){
//screen.bg = this.bg
//screen.redraw()
}
write(text, buttons, callback){
//$('#gametext > span').html(`<span>${text}</span>`)
//input.setText(buttons)
//input.bindAll(callback)
}
constructor(imgsrc, text, actions, callback){
let img = new Image()
img.src = imgsrc
this.bg = img
this.text = text
this.actions = actions
this.callback = callback
scenarioList.push(this)
console.log(scenarioList)
}
}
I init the class the following (and this is in the global scope)
new Scenario('./bg/1.png', 'You look around and see a huge mountain, what do you do?',[
'Climb It!!',
'Walk around',
'Other Direction',
'Rest',
], [
() => {
alert('a')
},
() => {
alert('a')
},
() => {
alert('a')
},
() => {
alert('a')
},
])
And verify with console.log(scenarioList)
[Scenario]
So its appended, but when I later try to do a console.log() on the same variable it is the following:
[]
Code that causes it:
const startGame = () => {
alert('were here') // this executes at the correct time, but later then variable init.
let scn = randomScenario()
console.log(scenarioList)
scn.write()
scn.setBG()
}
I am not seeing why this would happen, anyone can give me a push in the right direction?
I've found the solution, this code actually removed the element from the array:
const randomScenario = () => {
return scenarioList[Math.floor(Math.random() * scenarioList.length--)]
}
instead I did this:
return scenarioList[Math.floor(Math.random() * scenarioList.length -1)]

how to do pagination using mirage fake data in emberjs?

I am using mirage for creating fake data.
scenario/default.js
export default function(server) {
server.createList('product', 48);
server.loadFixtures();
}
Above I am creating 48 products and from controller I am calling
this.store.query('product', {
filter: {
limit: 10,
offset: 0
}
}).then((result) => {
console.log(result);
});
and in mirage/config.js
this.get('/products', function(db) {
let products = db.products;
return {
data: products.map(attrs => ({
type: 'product',
id: attrs.id,
attributes: attrs
}))
};
});
now my question is, how to load 10 products per page? I am sending in filter 10 as page size and offset means page number.
what changes should be done to config.js to load only limited products?
In your handler in mirage/config.js:
this.get('/products', function(db) {
let images = db.images;
return {
data: images.map(attrs => ({
type: 'product',
id: attrs.id,
attributes: attrs
}))
};
});
You are able to access the request object like so:
this.get('/products', function(db, request) {
let images = db.images;
//use request to limit images here
return {
data: images.map(attrs => ({
type: 'product',
id: attrs.id,
attributes: attrs
}))
};
});
Have a look at this twiddle for a full example.
Where the this twiddle has the following:
this.get('tasks',function(schema, request){
let qp = request.queryParams
let page = parseInt(qp.page)
let limit = parseInt(qp.limit)
let start = page * limit
let end = start + limit
let filtered = tasks.slice(start,end)
return {
data: filtered
}
})
You'll just adapt it for your use like this:
this.get('products',function(db, request){
let qp = request.queryParams
let offset = parseInt(qp.offset)
let limit = parseInt(qp.limit)
let start = offset * limit
let end = start + limit
let images = db.images.slice(start,end)
return {
data: images.map(attrs => ({
type: 'product',
id: attrs.id,
attributes: attrs
}))
}
})
An example with todos, you can adapt it to your own use case.
// Fetch all todos
this.get("/todos", (schema, request) => {
const {queryParams: { pageOffset, pageSize }} = request
const todos = schema.db.todos;
if (Number(pageSize)) {
const start = Number(pageSize) * Number(pageOffset)
const end = start + Number(pageSize)
const page = todos.slice(start, end)
return {
items: page,
nextPage: todos.length > end ? Number(pageOffset) + 1 : undefined,
}
}
return todos
});

Categories