Rally Ext JS change functionalty of existing component - extjs

I am trying to either override or extend an existing component - the Rally.ui.PercentDone component. I want to provide it with a portfolio item with all the data necessary to render it using the same color coding Rally native apps use (the Rally Health Color Calculator).
I really just need the function to pass the correct record. Here is my idea so far:
Ext.define('Custom.PercentDone', {
requires: ['Rally.ui.renderer.template.progressbar.PortfolioItemPercentDoneTemplate', 'Rally.util.HealthColorCalculator'],
extend : 'Rally.ui.PercentDone',
alias : 'widget.cpercentdone',
config: {
record: null
},
constructor: function(config) {
config = this.config;
this.renderTpl = Ext.create('Custom.renderer.template.progressbar.PercentDoneTemplate', {
calculateColorFn: Ext.bind(function(recordData) {
console.log('called my custom coloring fn');
var colorObject = Rally.util.HealthColorCalculator.calculateHealthColorForPortfolioItemData(config.record, config.percentDoneName);
return colorObject.hex;
}, this)
});
this.renderData = config;
this.mergeConfig(config);
this.callParent([this.config]);
}
});
var custom = Ext.create('Custom.PercentDone', {
record: item,
percentDoneName: 'PercentDoneByStoryPlanEstimate',
});
but my calculate color function is not being called instead of the default.
I got it to work by overriding:
var percentDoneByStoryCountEl = Ext.create("Rally.ui.PercentDone", {
record: item,
percentDoneName: "PercentDoneByStoryCount",
percentDone: item.PercentDoneByStoryCount
});
tpl = percentDoneByStoryCountEl.renderTpl;
tpl.calculateColorFn = function (recordData) {
var colorObject = Rally.util.HealthColorCalculator.calculateHealthColorForPortfolioItemData(item, "PercentDoneByStoryCount");
return colorObject.hex;
};
Ext.override(percentDoneByStoryCountEl, {
renderTpl: tpl
});
but I would like to figure out how to do it via extending the component instead.
Thanks for your help.

Related

ExtJS 6.7 - How to attach blur and focus events on every form copoment?

I'd like to mark each field wrapping container with custom css class when field is focused and remove that class when field is blured. So I would like to attach focus/blur event methods to every form field component I add to any form.
in Ext 4 I did it like this:
Ext.ComponentManager.all.on('add', function(map, key, item) {
// Check if item is a Window and do whatever
if (item instanceof Ext.form.field.Base) {
item.on('focus', function(theField) {
var parentDom = null; //theField.bodyEl.findParent('.x-form-fieldcontainer');
if (!parentDom) {
parentDom = theField.bodyEl.findParent('.x-field');
}
if (parentDom) {
var parentEl = Ext.get(parentDom);
parentEl.addCls('focused-field');
}
}, item);
item.on('blur', function(theField) {
var parentDom = null; //theField.bodyEl.findParent('.x-form-fieldcontainer');
if (!parentDom) {
parentDom = theField.bodyEl.findParent('.x-field');
}
if (parentDom) {
var parentEl = Ext.get(parentDom);
parentEl.removeCls('focused-field');
}
}, item);
}
});
I'm not sure how to do it in ExtJS 6
Any help appreciated
Regards
Armando
You don`t need it, ExtJs has already '.x-field-focus' css class which is added to wrapper element on focus, so you can try to add your styles to the existing class. You can also look at the $form-field-focus-* theme variables..
Anyway, if you want to add this functionality, you can override the 'Ext.form.field.Base' class which is the parent of all the form fields.
Something like this:
Ext.define('overrides.form.field.Base', {
override: 'Ext.form.field.Base',
customCssOnFocus: 'focused-field',
initEvents: function() {
this.callParent(arguments);
this.on('focus', this.addCustomCssOnFocus, this);
this.on('blur', this.removeCustomCssOnBlur, this);
},
addCustomCssOnFocus: function() {
Ext.get(this.getEl().findParent('.x-field')).addCls(this.customCssOnFocus);
},
removeCustomCssOnBlur: function() {
Ext.get(this.getEl().findParent('.x-field')).removeCls(this.customCssOnFocus);
}
});

Binding Angular2 components inside of a Jquery plugin template

I'm working on using a kendo inside of an angular 2 project.
Getting the widget set up correctly is no problem:
ngOnInit() {
let options = inputsToOptionObject(KendoUIScheduler, this);
options.dataBound = this.bound;
this.scheduler = $(this.element.nativeElement)
.kendoScheduler(options)
.data('kendoScheduler');
}
When that runs, the plugin modifies the DOM (and, to my knowleged, without modifiying the shadow DOM maintained by angular2). My issue is that if I want to use a component anywhere inside of the plugin, like in a template, Angular is unaware of it's existence and won't bind it.
Example:
public views:kendo.ui.SchedulerView[] = [{
type: 'month',
title: 'test',
dayTemplate: (x:any) => {
let date = x.date.getDate();
let count = this.data[date];
return `<monthly-scheduler-day [date]="test" [count]=${count}"></monthly-scheduler-day>`
}
}];
The monthly-scheduler-day class:
#Component({
selector: 'monthly-scheduler-day',
template: `
<div>{{date}}</div>
<div class="badge" (click)=dayClick($event)>Available</div>
`
})
export class MonthlySchedulerDayComponent implements OnInit{
#Input() date: number;
#Input() count: number;
constructor() {
console.log('constructed');
}
ngOnInit(){
console.log('created');
}
dayClick(event){
console.log('clicked a day');
}
}
Is there a "right" way to bind these components inside of the markup created by the widget? I've managed to do it by listening for the bind event from the widget and then looping over the elements it created and using the DynamicComponentLoader, but it feels wrong.
I found some of the details I needed in this thread: https://github.com/angular/angular/issues/6223
I whipped this service up to handle binding my components:
import { Injectable, ComponentMetadata, ViewContainerRef, ComponentResolver, ComponentRef, Injector } from '#angular/core';
declare var $:JQueryStatic;
#Injectable()
export class JQueryBinder {
constructor(
private resolver: ComponentResolver,
private injector: Injector
){}
public bindAll(
componentType: any,
contextParser:(html:string)=>{},
componentInitializer:(c: ComponentRef<any>, context: {})=>void):
void
{
let selector = Reflect.getMetadata('annotations', componentType).find((a:any) => {
return a instanceof ComponentMetadata
}).selector;
this.resolver.resolveComponent(componentType).then((factory)=> {
$(selector).each((i,e) => {
let context = contextParser($(e).html());
let c = factory.create(this.injector, null, e);
componentInitializer(c, context);
c.changeDetectorRef.detectChanges();
c.onDestroy(()=>{
c.changeDetectorRef.detach();
})
});
});
}
}
Params:
componentType: The component class you want to bind. It uses reflection to pull the selector it needs
contextParser: callback that takes the existing child html and constructs a context object (anything you need to initialize the component state)
componentInitializer - callback that initializes the created component with the context you parsed
Example usage:
let parser = (html: string) => {
return {
date: parseInt(html)
};
};
let initer = (c: ComponentRef<GridCellComponent>, context: { date: number })=>{
let d = context.date;
c.instance.count = this.data[d];
c.instance.date = d;
}
this.binder.bindAll(GridCellComponent, parser, initer );
Well your solution works fine until the component needs to change its state and rerender some stuff.
Because I haven't found yet any ability to get ViewContainerRef for an element generated outside of Angular (jquery, vanilla js or even server-side)
the first idea was to call detectChanges() by setting up an interval. And after several iterations finally I came to a solution which works for me.
So far in 2017 you have to replace ComponentResolver with ComponentResolverFactory and do almost the same things:
let componentFactory = this.factoryResolver.resolveComponentFactory(componentType),
componentRef = componentFactory.create(this.injector, null, selectorOrNode);
componentRef.changeDetectorRef.detectChanges();
After that you can emulate attaching component instance to the change detection cycle by subscribing to EventEmitters of its NgZone:
let enumerateProperties = obj => Object.keys(obj).map(key => obj[key]),
properties = enumerateProperties(injector.get(NgZone))
.filter(p => p instanceof EventEmitter);
let subscriptions = Observable.merge(...properties)
.subscribe(_ => changeDetectorRef.detectChanges());
Of course don't forget to unsubscribe on destroy:
componentRef.onDestroy(_ => {
subscriptions.forEach(x => x.unsubscribe());
componentRef.changeDetectorRef.detach();
});
UPD after stackoverflowing once more
Forget all the words above. It works but just follow this answer

JsTree custom contextmenu in TypeScript

I try to use jstree control in my TypeScript code for an angularjs application. I use jstree typings and jstree.directive to show a tree. Everything works to the point when I need to handle menu item click and call for the base method. Inside of my action there is no "this" (contextmenu) scope. Any suggestions?
class MapTreeViewController {
mapTreeView: JSTree;
vm.mapTreeView = $('#jstree').jstree(
{
'core': { 'data': items },
'plugins': ['themes', 'ui', 'contextmenu'],
'contextmenu': {
'items': function(node:any) {
var vmNode = this;
return {
'rename': { // rename menu item
'label': 'Rename',
'action': function(obj) {
this.rename(obj);
}
}
};
}
}
});
}
Somewhere inside of a method.
this is not an instance - take a look at the original function to see how to obtain an instance:
https://github.com/vakata/jstree/blob/master/src/jstree.contextmenu.js#L84
"action" : function (data) {
var inst = $.jstree.reference(data.reference),
...

How to pass View Param to View Model DataSource in Kendo Mobile?

What is the correct way to pass a view variable from the URL to a View Model to filter the result?
For example:
dataSource: new kendo.DataSource( {
transport: {
read: {
url: 'http://api.endpoint.com/resource',
}
parameterMap: function(options,type) {
if (type === 'read') {
return {
FormID: view.params.FormID
};
}
}
});
In the example above, there's a parameter in the URL called "FormID" and I would like to pass that value right to the parameterMap function. There is no "view" object, so I'm just putting that as an example.
I tried hooking into to the "data-show" and "data-init" functions to set this value to use, but the datasource fetches the data before these functions run.
Thanks
The configuration option options.transport.read can be a function, so you can compose the url there:
dataSource: new kendo.DataSource({
transport: {
read: function (options) {
// get the id from wherever it is stored (e.g. your list view)
var resourceId = getResourceId();
$.ajax({
url: 'http://api.endpoint.com/resource/' + resourceId,
dataType: "jsonp",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
}
}
});
To connect this with your list view, you could use the listview's change event:
data-bind="source: pnrfeedsDataSource, events: { change: onListViewChange }"
then in viewModel.onListViewChange you could set the appropriate resource id for the item that was clicked on:
// the view model you bind the list view to
var viewModel = kendo.observable({
// ..., your other properties
onListViewChange: function (e) {
var element = e.sender.select(); // clicked list element
var uid = $(element).data("uid");
var dataItem = this.dataSource.getByUid(uid);
// assuming your data item in the data source has the id
// in dataItem.ResourceId
this._selectedResource = dataItem.ResourceId;
}
});
Then getResourceId() could get it from viewModel._selectedResource (or it could be a getter on the viewModel itself). I'm not sure how all of this is structured in your code, so it's difficult to give more advice; maybe you could add a link to jsfiddle for illustration.
You may use a "global" variable or a field in the viewmodel for that purpose. Something like
var vm = kendo.observable({
FormID: null,
dataSource: new kendo.DataSource( {
transport: {
read: {
url: 'http://api.endpoint.com/resource',
}
parameterMap: function(options,type) {
if (type === 'read') {
return {
FormID: vm.FormID
};
}
}
})
});
function viewShow(e) {
vm.set("FormID", e.view.params.FormID);
// at this point it is usually a good idea to invoke the datasource read() method.
vm.dataSource.read();
}
The datasource will fetch the data before the view show event if a widget is bound to it. You can work around this problem by setting the widget autoBind configuration option to false - all data-bound Kendo UI widgets support it.

Backbone Boilerplate Layout Manager

Can someone help explain / provide an example on how to use the LayoutManager within the Backbone Bolierplate?
Within app.js I can see a useLayout function that extends the main app object. Within here it appears to be setting a base layout element:
// Helper for using layouts.
useLayout: function(name, options) {
// Enable variable arity by allowing the first argument to be the options
// object and omitting the name argument.
if (_.isObject(name)) {
options = name;
}
// Ensure options is an object.
options = options || {};
// If a name property was specified use that as the template.
if (_.isString(name)) {
options.template = name;
}
// Create a new Layout with options.
var layout = new Backbone.Layout(_.extend({
el: "#main"
}, options));
// Cache the refererence.
return this.layout = layout;
}
Is that correct? If so, do I somehow the use the 'UseLayout' function with the applications Router? ...to add different UI elements/nested views to the main view?
Thanks.
I will usually have an "app" object that stores all my settings needed throughout the application. This object then extends some useful functions like the one you listed above. For example:
var app = {
// The root path to run the application.
root: "/",
anotherGlobalValue: "something",
apiUrl: "http://some.url"
};
// Mix Backbone.Events, modules, and layout management into the app object.
return _.extend(app, {
// Create a custom object with a nested Views object.
module: function(additionalProps) {
return _.extend({ Views: {} }, additionalProps);
},
// Helper for using layouts.
useLayout: function(options) {
// Create a new Layout with options.
var layout = new Backbone.Layout(_.extend({
el: "#main"
}, options));
return this.layout = layout;
},
// Helper for using form layouts.
anotherUsefulFunction: function(options) {
// Something useful
}
}, Backbone.Events);
});
Now in my router I would do something like:
app.useLayout({ template: "layout/home" })
.setViews({
".promotional-items": new Promotions.Views.PromotionNavigation(),
".featured-container": new Media.Views.FeaturedSlider({
vehicles: app.vehicles,
collection: featuredCollection
})
}).render().then(function() {
//Do something once the layout has rendered.
});
I have just taken a sample from one of my applications, but I am sure you can get the idea. My main layout is basically just a layout template file which holds the elements so the views can be injected into their respective holders.
You would use it as if you're using a regular Backbone View. Instead of building the View directly, you can use this to create a new instance. The code you posted is a wrapper object on top of the Backbone Layout Manager extension with el: #main set as the default View element which is overridable.
var layout = new useLayout({ template: "#viewElement", ... });

Resources