How to get DetailsList/Selection component on React Fabric UI to work with ReactHooks? - react-hooks

I'm having issue getting the React Fabric UI DetailsList to work with React Hooks. It renders, but the selection part does not. Whenever, you select a row, I expect the count of the selection to be updated. However, i'm not seeing that. It looks like the selection component items never get updated even thou the UI shows it being selected. I'm also seeing the onSelectionChange being triggered when you select a row. Now sure if its because i'm using react hooks or what
I took the provided class example which works:
[Codepen]https://codepen.io/pen/?&editable=true (Example)
Same as the original but stripped down
[Codepen]https://codepen.io/darewreckk/pen/NQRWEd?editors=1111
converted it to a react hook component. I would expect the same thing, but i'm not and can't figure out what's different.
Modified Example with Hooks
[Codepen]https://codepen.io/darewreckk/pen/GVjRNb?editors=1111
Any advice appreciated,
Thanks,
Derek

The selection count is stored on the Selection object that you are creating. You could log it out like so:
const _selection = new Selection({
onSelectionChanged: () => {
console.log('Selected count:' + _selection.count);
}
});
You can set the value of selectionCount and selectionDetails whenever onSelectionChanged is called:
const _selection = new Selection({
onSelectionChanged: () => {
setSelectionCount(_selection.count);
setSelectionDetails(`${_selection.count} items selected`)
}
});
As a side note: If you want selectionDetails to update when selectionCount updates, you can use the useEffect hook:
React.useEffect(() => {
setSelectionDetails(`${selectionCount} items selected`);
}, [selectionCount]);
The above effect will run whenever selectionCount updates, and so in turn update selectionDetails.

Related

Ajaxinate Endless scolling has stopped product Quick View from working

I am using Shopify "Streamline Theme" with quick product view and I recently added infinite scroll to products on each collection using Ajaxinate.js.
When I open a collection page it loads with some products which is supposed to do, The products already there work fine with quick view and quick add to cart and also.
The Infinite scroll works fine and it loads new product fine but the problem is raised when the new products loaded through AJAX call doesn't have work with the quick view function.
I have tried to create a callback function to activate the quick view with no success, using the theme initialisation code with no success.
function callBack(){
theme.init();
theme.initQuickShop();
};
document.addEventListener("DOMContentLoaded", function() {
var endlessClick = new Ajaxinate({
method: "scroll",
loadingText: 'Loading...',
callback: callBack
});
});
Edit -------
My problem, is that when the page is loaded only the initial loaded products quickview elements are loaded in the DOM. When the scroll more button is clicked, the newly loaded products are loaded without their respective quickview elements. Hence why the quickview does't work for them. The theme.js file comes with this initialisation code:
theme.reinitProductGridItem = function($scope) {
if (AOS) {
AOS.refreshHard();
}
if (theme.settings.currenciesEnabled) {
theme.currencySwitcher.ajaxrefresh();
}
// Reload quick shop buttons
theme.initQuickShop(true);
// Refresh reviews app
if (window.SPR) {
SPR.initDomEls();SPR.loadBadges();
}
// Re-register product templates in quick view modals.
// Will not double-register.
sections.register('product-template', theme.Product, $scope);
// Re-hook up collapsible box triggers
theme.collapsibles.init();
};
I have tried to integrate this into a callback but no success, the quickview modal doesn't seem to load for the newly loaded products:
function callBack(){
ReloadSmartWishlist();
var $container = $('#CollectionSection');
theme.reinitProductGridItem($container);
// I have tried the following init qith no success:
// theme.init();
// theme.initQuickShop(true);
// theme.initQuickShop();
// sections.register('product-template', theme.Product, $container);
// AOS.refreshHard();
};
document.addEventListener("DOMContentLoaded", function() {
var endlessClick = new Ajaxinate({
method: "click",
loadingText: 'Loading...',
offset: 0,
callback: callBack
});
});
I am missing something but what? :/
Note for other things like loading products images with the callback and the wishlist app, it works as intended...
When you load elements via AJAX and if the events are not attached to a parent element that is not removed from the DOM, those elements will not have an attached event to them.
The term used here is event delegation.
Here is an example of non-delegated event:
document.querySelectorAll('a').addEventListener('click', function(){
// Do something
})
Since you are attaching the event to the existing "a" elements if you add new 'a' via AJAX those elements will not have the event since Javascript already attached all the events and it will not reattach them if you don't specifically recall them again.
Here is an example of a delegated event:
document.querySelector('body').addEventListener('click', function(target){
let target = event.target;
if (target.tagName === 'A'){
// Do something here
}
})
Where we attach the event to the body tag ( where it's a better idea to attach it to a closer none-modified parent element of the ajax items ) and once we click we check if our target tag is an "a" and do something then.
So long story short, you will need to delegate the quick cart link so that it works after you load the items via AJAX.
Drip is correct you need to delegate your event, but for people like me it's hard to completely understand how to do that.
I'm not sure how your quickview is structured, but if you open it with a .click function and can use jquery use the [.on() function][1].
For example: I use a quickview that opens on a button click. My button is attached to my product-grid-item.liquid with this bit of code:
<div class="quick-view-button">
<a class="quick-view" data-handle="{{ product.handle }}" href="javascript:void(0);">Quick View</a>
</div>
My quickview function originally looked like this:
function quickView() {
$(".quick-view").click(function () {
//all of the quickview code
What happens is exactly like you described. The event listeners only loaded on the first product load but nothing after an AJAX load.
Using jquery's .on() binds the event listener to the element meaning when it's loaded in later it'll still have the event. Here's an example of what my code looks like after using .on()
function quickView() {
$('body').on('click','.quick-view',function(){
I really hope this helps you or someone else with this problem.
[1]: http://api.jquery.com/on/

CKEditor 5 how to get the click, update and deleted events from any widget/Model/View

How can I get notified on a CKEditor 5 model, View and widget's click, update and delete events?
Let's assume that I have a custom plugin implementation similar to a link plugin or highlighter plugin. Now, how can I get the following events?
When user clicks on the link/highlighted element.
When user updates the inner content of the highlighted element.
When user removes the entire highlighted link or highlighter element from editor.
The element can be a model element/view element/or a widget.
Here is the code I use. It need to be in the init() method for a plugin. I don't know if this is the correct way to do it, but it works for me(tm).
const editor = this.editor;
const model=editor.model;
const editingView=editor.editing.view;
editingView.addObserver( ClickObserver );
const viewDocument = editor.editing.view.document;
this.listenTo( viewDocument, 'click', (event,data) => {
const target=data.target; // This is the view the user clicked on
const modelObj=editor.editing.mapper.toModelElement(target);
// modelObj is the model object for the element the user clicked on. Now you just need to test if clicking on this model is something you are interested in.
// console.log(modelObj);
} );
Note that this does seem to fail if you click on a AttributeElement (Such as bold text). In that case you can either call on the target.parent until you get a result.

Fullcalendar Problems w/ filtering Events in agendaDay-View (works only one time, then no more events exist)

I have a problem with filtering events:
I use fullcalender in agendaDay-View
I use a drop-Down list to select a driver
I compare the name (it is a property of event-object) with the selected value
(this part is ok)
Then,
I remove all Events (.fullCalendar('removeEvents');)
Add the specific events
(add with renderEvents doesn't work proberly at the moment)
And now my problem appears:
For the first time it works, however, when I select another 'driver', the events are gone, because of the 'removeEvents'-Action before.
So, how can I solve this problem, that I can only display the filtered events and keep the other (actualley all events) to filter again for second, third n- time?
$('#' + id).fullCalendar('refetchEvents');
was the first idea, however, its brings all back and selected Issues were doubled (and so on).
I'm thankful for every hint.
Ok I think you can solve your problem with fullCalendar's eventRender function.
The function can also return false to completely cancel the rendering of the event.
Your event from events.json should have a property like 'driver_id'.
I would have select field instead of dropdown with option keys being driver ids, values - names or whatever. Lets say it's id would be 'driver_select'.
Then render events like this:
$('#calendar').fullCalendar({
//...
eventRender: function(event, element) {
//driver select should have default value assigned or else no events will be rendered
if ($("#driver_select").val() !== event.driver_id) {
return false; //do not render other driver events
}
}
//...
});
Handle select changes to update
$("#driver_select").off('change').on('change', function() {
$("#calendar").fullCalendar( 'refetchEvents' );
});
Another approach would be to show all drivers in a timeline. For that you can use FullCalendar Scheduler.

Ionic 2: publish multiple events on Modal dismiss sometimes doesn't work

I've got a modal window that when you click 'Add', it does its thing, dismisses, and then when the promise is resolved, publishes some events that tell relevant components to update:
this._viewControl.dismiss().then(() =>
this._events.publish('update_myJobsPage', null);
this._events.publish('update_assessmentsPage', null);
this._events.publish('update_buildingPage', null);
});
Problem is, sometimes it works and they update their views, sometimes not. The modal always dismisses and the events fire though.
Am I doing something fundamentally wrong here?
Thanks.
Problem is, sometimes it works and they update their views, sometimes
not.
As you can read in this answer, Application state change is caused by three things:
1) Events - User events like click, change, input, submit, …
2) XMLHttpRequests - E.g. when fetching data from a remote service Timers -
3) setTimeout(),setInterval(), because JavaScript
It turns out that these are the only cases when Angular is actually interested in updating the view.
So if you want to update other things outside Angular way, you will have to let Angular know that something has changed and needs to we aware of updating things. You can do this by first importing ngZone like this:
import { ..., NgZone } from '#angular/core';
Declaring it in your constructor like this:
constructor(..., private ngZone: NgZone ) { //... }
And then surrounding your code inside a zone
this._viewControl.dismiss().then(() =>
this.ngZone.run(() => {
// Execute here what you want and Angular will update the view for you.
// ...
this._events.publish('update_myJobsPage', null);
this._events.publish('update_assessmentsPage', null);
this._events.publish('update_buildingPage', null);
});
});
Have you tried onDismiss ?
this._viewControl.onDismiss(() => {
this._events.publish('update_myJobsPage', null);
this._events.publish('update_assessmentsPage', null);
this._events.publish('update_buildingPage', null);
});
So, it turns out, if I empty out my collection when I'm refreshing, so..
e.g
updatePage() {
this.myCollection = [];
this.someService.getItems().then(items => {
this.myCollection = items;
});
}
then the page always shows the update. So I'm going to put this one down to a timing/change detection bug in Angular 2 and move on!

Titanium Mobile: reference UI elements with an ID?

How do you keep track of your UI elements in Titanium? Say you have a window with a TableView that has some Switches (on/off) in it and you'd like to reference the changed switch onchange with a generic event listener. There's the property event.source, but you still don't really know what field of a form was just toggled, you just have a reference to the element. Is there a way to give the element an ID, as you would with a radiobutton in JavaScript?
Up to now, registered each form UI element in a dictionary, and saved all the values at once, looping through the dictionary and getting each object value. But now I'd like to do this onchange, and I can't find any other way to do it than create a specific callback function for each element (which I'd really rather not).
just assign and id to the element... all of these other solution CAN work, but they seem to be over kill for what you are asking for.
// create switch with id
var switcher0 = Ti.Ui.createSwitch({id:"switch1"});
then inside your event listener
myform.addEventListener('click', function(e){
var obj = e.source;
if ( obj.id == "switch1" ) {
// do some magic!!
}
});
A simple solution is to use a framework that helps you keep track of all your elements, which speeds up development quite a bit, as the project and app grows. I've built a framework of my own called Adamantium.js, which lets you use a syntax like jQuery to deal with your elements, based on ID and type selectors. In a coming release, it will also support for something like classes, that can be arbitrarily added or removed from an element, tracking of master/slave relationships and basic filter methods, to help you narrow your query. Most methods are chainable, so building apps with rich interaction is quick and simple.
A quick demo:
// Type selector, selects all switches
$(':Switch')
// Bind a callback to the change event on all switches
// This callback is also inherited by all new switch elements
$(':Switch').bind('change', function (e) {
alert(e.type + ' fired on ' + e.source.id + ', value = ' + e.value);
});
// Select by ID and trigger an event
$('#MyCustomSwitch').trigger('change', {
foo: 'bar'
});
Then there's a lot of other cool methods in the framework, that are all designed to speed up development and modeled after the familiar ways of jQuery, more about that in the original blog post.
I completely understand not wanting to write a listener to each one because that is very time consuming. I had the same problem that you did and solved it like so.
var switches = [];
function createSwitch(i) {
switches[i] = Ti.UI.createSwitch();
switches[i].addEventListener('change', function(e) {
Ti.API.info('switch '+i+' = '+e.value);
});
return switches[i];
}
for(i=0;i<rows.length;i++) {
row = Ti.UI.createTableViewRow();
row.add(createSwitch(i));
}
However keep in mind that this solution may not fit your needs as it did mine. For me it was good because each time I created a switch it added a listener to it dynamically then I could simply get the e.source.parent of the switch to interact with whatever I needed.
module Id just for the hold it's ID. When we have use id the call any another space just use . and use easily.
Try This
var but1 = Ti.Ui.createButton({title : 'Button', id:"1"});
window.addEventListener('click', function(e){
var obj = e.source;
if ( obj.id == "1" ) {
// do some magic!!
}
});
window.add(but1);
I, think this is supported for you.
how do you create your tableview and your switcher? usually i would define a eventListener function while creating the switcher.
// first switch
var switcher0 = Ti.Ui.createSwitch();
switch0.addEventListener('change',function(e){});
myTableViewRow.add(switch0);
myTableView.add(myTableViewRow);
// second switch
var switch1 = ..
so no generic event listener is needed.

Resources