call parent class function on extjs 3 - class

i have extjs class like this for Add:
Ext.ns('Example');
Example.Form = Ext.extend(Ext.form.FormPanel, {
,initComponent:function() {
// hard coded - cannot be changed from outsid
var config = {
items: [{
xtype: 'textfield',
fieldLabel: 'title',
name: 'author',
allowBlank: false
}
.........................
]
,buttons:[
{
text:'submit'
,formBind:true
,scope:this
,handler:this.submit
}]
}; // eo config object
// apply config
Ext.apply(this, Ext.apply(this.initialConfig, config));
// call parent
Example.Form.superclass.initComponent.apply(this, arguments);
} // eo function initComponent
/**
* Form onRender override
*/
,onRender:function() {
..................
} // eo function onRender
/**
* Reset
*/
,reset:function() {
this.getForm().reset();
} // eo function onRender
/**
* Load button click handler
*/
,onLoadClick:function() {
....................
}
,submit:function() {
........................
}
,onSuccess:function(form, action) {
..........................
}
,onFailure:function(form, action) {
......................
} // eo function onFailure
,showError:function(msg, title) {
........................
});
}
});
and i have another extend for Edit:
Example.Form2 = Ext.extend(Example.Form, {
......
});
how i can call "onLoadClick" function from first class in secound class?because i want to load data to my form before form load.

If you have one class that extends another class you can call the "parent" class methods by using the superclass property on your class definition.
In the example below we add a special function mySpecial add and make it call the parent classes add function.
Ext.ux.myForm = Ext.extend(Ext.form.FormPanel, {
...
mySpecialAdd: function(comp, anExtraParam) {
// some special handling here
...
// call parent class add
return Ext.ux.myForm.superclass.add.call(this, comp);
}
})
instead of call you can also choose to use apply
Ext.ux.myForm = Ext.extend(Ext.form.FormPanel, {
...
mySpecialAdd: function(comp, anExtraParam) {
// some special handling here
...
// call parent class add
return Ext.ux.myForm.superclass.add.apply(this, [comp]);
}
})
Do note that "this" will still be your new class, so any other function that you overwrite will be the one called from the parent class and not the parent class function.
Example
Ext.form.FormPanel have an onAdd method that is being called in Ext.form.FormPanel.add, so if you overwrite onAdd then its your function that is called.
Ext.ux.myForm = Ext.extend(Ext.form.FormPanel, {
...
mySpecialAdd: function(comp, anExtraParam) {
// some special handling here
...
// call parent class add
return Ext.ux.myForm.superclass.add.apply(this, [comp]);
},
// even though onAdd is marked as private you are actually still overwriting it here
// because of the way its implemented in Ext 3
onAdd: function(c) {
// this will get called from the parent class (Ext.form.FormPanel) add method.
...
// so make sure you handle it nicely
Ext.ux.myForm.superclass.onAdd.call(this, c);
...
}
})

If you need to call a superclass method into a method of the subclass, you can do something like this:
Example.Form2 = Ext.extend(Example.Form, {
testMethod: function(){
...
//call parent class method
Example.Form2.superclass.doLoadClick.call(this);
...
}
});
Is that what you mean ?

Related

How to Register custom handelbars helper in assemble 0.17.1

In my assemblefile.js I try to register a custom helper. The helper itself does work since i have it in use in a grunt project with assemble.
assemble: {
options: {
helpers: ['./src/helper/custom-helper.js' ]
}
}
In assemble 0.17.1 I tried it like this but it doesn´t work. Does anyone know how to do this?
app.helpers('./src/helper/custom-helper.js');
custom-helper.js:
module.exports.register = function (Handlebars, options, params) {
Handlebars.registerHelper('section', function(name, options) {
if (!this.sections) {
this.sections = {};
}
this.sections[name] = options.fn(this);
return null;;
});
};
assemble is built on top of the templates module now, so you can use the .helper and .helpers methods for registering helpers with assemble, which will register them with Handlebars. This link has more information on registering the helpers.
Since the templates api is used, you don't have to wrap the helpers with the .register method in your example. You can just export the helper function, then name it when registering with assemble like this:
// custom-helper.js
module.exports = function(name, options) {
if (!this.sections) {
this.sections = {};
}
this.sections[name] = options.fn(this);
return null;
};
// register with assemble
var app = assemble();
app.helper('section', require('./custom-helper.js'));
You may also export an object with helpers and register them all at once using the .helpers method:
// my-helpers.js
module.exports = {
foo: function(str) { return 'FOO: ' + str; },
bar: function(str) { return 'BAR: ' + str; },
baz: function(str) { return 'BAZ: ' + str; }
};
// register with assemble
var app = assemble();
app.helpers(require('./my-helpers.js'));
When registering the object with the .helpers method, the property keys are used for the helper names

How to use node-simple-schema reactively?

Given that there is not much examples about this, I am following the docs as best as I can, but the validation is not reactive.
I declare a schema :
import { Tracker } from 'meteor/tracker';
import SimpleSchema from 'simpl-schema';
export const modelSchema = new SimpleSchema({
foo: {
type: String,
custom() {
setTimeout(() => {
this.addValidationErrors([{ name: 'foo', type: 'notUnique' }]);
}, 100); // simulate async
return false;
}
}
}, {
tracker: Tracker
});
then I use this schema in my component :
export default class InventoryItemForm extends TrackerReact(Component) {
constructor(props) {
super(props);
this.validation = modelSchema.newContext();
this.state = {
isValid: this.validation.isValid()
};
}
...
render() {
...
const errors = this.validation._validationErrors;
return (
...
)
}
}
So, whenever I try to validate foo, the asynchronous' custom function is called, and the proper addValidationErrors function is called, but the component is never re-rendered when this.validation.isValid() is supposed to be false.
What am I missing?
There are actually two errors in your code. Firstly this.addValidationErrors cannot be used asynchronously inside custom validation, as it does not refer to the correct validation context. Secondly, TrackerReact only registers reactive data sources (such as .isValid) inside the render function, so it's not sufficient to only access _validationErrors in it. Thus to get it working you need to use a named validation context, and call isValid in the render function (or some other function called by it) like this:
in the validation
custom() {
setTimeout(() => {
modelSchema.namedContext().addValidationErrors([
{ name: 'foo', type: 'notUnique' }
]);
}, 100);
}
the component
export default class InventoryItemForm extends TrackerReact(Component) {
constructor(props) {
super(props);
this.validation = modelSchema.namedContext();
}
render() {
let errors = [];
if (!this.validation.isValid()) {
errors = this.validation._validationErrors;
}
return (
...
)
}
}
See more about asynchronous validation here.

React, get bound parent dom element name within component

Within my component, how can I access the name of the parent component it is nested inside?
So if my render is thus:
ReactDOM.render(
<RadialsDisplay data={imagedata}/>,
document.getElementById('radials-1')
);
How can I retrieve the id name #radials-1 from within the component itself?
It probably makes the most sense to pass it as a property, but if you really need to get it programmatically, and from inside the component, you can wait for the component to mount, find its DOM node, and then look at its parent.
Here's an example:
class Application extends React.Component {
constructor() {
super();
this.state = { containerId: "" };
}
componentDidMount() {
this.setState({
containerId: ReactDOM.findDOMNode(this).parentNode.getAttribute("id")
});
}
render() {
return <div>My container's ID is: {this.state.containerId}</div>;
}
}
ReactDOM.render(<Application />, document.getElementById("react-app-container"));
Working demo: https://jsbin.com/yayepa/1/edit?html,js,output
If you do this a lot, or want to be really fancy, you could utilize a higher-order component:
class ContainerIdDetector extends React.Component {
constructor() {
super();
this.state = { containerId: "" };
}
componentDidMount() {
this.setState({
containerId: ReactDOM.findDOMNode(this).parentNode.getAttribute("id")
});
}
render() {
if (!this.state.containerId) {
return <span />;
} else {
return React.cloneElement(
React.Children.only(this.props.children),
{ [this.props.property]: this.state.containerId }
);
}
}
}
ContainerIdDetector.propTypes = {
property: React.PropTypes.string.isRequired
}
// Takes an optional property name `property` and returns a function. This
// returned function takes a component class and returns a new one
// that, when rendered, automatically receives the ID of its parent
// DOM node on the property identified by `property`.
function withContainerId(property = "containerId") {
return (Component) => (props) =>
<ContainerIdDetector property={property}>
<Component {...props} />
</ContainerIdDetector>
}
Here, withContainerId is a function that takes an argument called property and returns a new function. This function can take a component type as its only argument, and returns a higher-order component. When rendered, the new component will render the passed component, with all its original props, plus an additional prop specifying the parent container's ID on the property specified by the property argument.
You can use them with ES7 decorators (as currently implemented) if you wish, or via a regular function call:
#withContainerId()
class Application extends React.Component {
render() {
return <div>My containers ID is: {this.props.containerId}</div>;
}
}
// or, if you don't use decorators:
//
// Application = withContainerId()(Application);
ReactDOM.render(<Application />, document.getElementById("react-app-container"));
Working demo: https://jsbin.com/zozumi/edit?html,js,output

Pass a controller to $ionicModal

I am wondering if you can pass a controller to the $ionicModal service. Something like.
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope,
controller: 'MyModalCotroller'
})
A little context: I would like to have a modal that is distributed across the app and I dont want to repeat all the methods (hide, show, buttons inside the modal) in every controller and I would like to remove the methods from the 'Main Controller' to keep things clean. This would encapsulate the functionality of the modal.
Is there a way to do this.?
Thanks
Just add the controller you want to use in the body of the html of the modal. I created a fiddle to show you an example based off the one provided in the ionic docs: http://jsfiddle.net/g6pdkfL8/
But basically:
<-- template for the modal window -->
<ion-modal-view>
<ion-content ng-controller="ModalController">
...
</ion-content>
<ion-modal-view>
There's no direct way of doing so in ionic. However, if you really want to have some common code being segregated at one place,
You can use services to do so. Here' how.
In your modal declaration, pass scope as null, also the modal declaration should move in a service.
app.service('utilsService', function($ionicModal) {
this.showModal = function() {
var service = this;
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: null,
controller: 'MyModalCotroller'
}).then(function(modal) {
service.modal = modal;
service.modal.show();
});
};
this.hideModal = function() {
this.modal.hide();
};
});
All your common methods will also move down into the same service.
Add the reference to this service into your controller's scope.
app.controller('indexController', function($scope, utilsService) {
$scope.utilsService = utilsService;
});
Now, you can call all the common methods from the view directly using this service.
e.g. <button ng-click="utilsService.hideModal()">Hide modal</button>
Based on this question and other needs I create a service that can be useful.
Anyway use the CodePen code, this updated, improved and it makes available the parameter 'options' of $ionicModal.
See this post: Ionic modal service or see in operation: CodePen
(function () {
'use strict';
var serviceId = 'appModalService';
angular.module('app').factory(serviceId, [
'$ionicModal', '$rootScope', '$q', '$injector', '$controller', appModalService
]);
function appModalService($ionicModal, $rootScope, $q, $injector, $controller) {
return {
show: show
}
function show(templateUrl, controller, parameters) {
// Grab the injector and create a new scope
var deferred = $q.defer(),
ctrlInstance,
modalScope = $rootScope.$new(),
thisScopeId = modalScope.$id;
$ionicModal.fromTemplateUrl(templateUrl, {
scope: modalScope,
animation: 'slide-in-up'
}).then(function (modal) {
modalScope.modal = modal;
modalScope.openModal = function () {
modalScope.modal.show();
};
modalScope.closeModal = function (result) {
deferred.resolve(result);
modalScope.modal.hide();
};
modalScope.$on('modal.hidden', function (thisModal) {
if (thisModal.currentScope) {
var modalScopeId = thisModal.currentScope.$id;
if (thisScopeId === modalScopeId) {
deferred.resolve(null);
_cleanup(thisModal.currentScope);
}
}
});
// Invoke the controller
var locals = { '$scope': modalScope, 'parameters': parameters };
var ctrlEval = _evalController(controller);
ctrlInstance = $controller(controller, locals);
if (ctrlEval.isControllerAs) {
ctrlInstance.openModal = modalScope.openModal;
ctrlInstance.closeModal = modalScope.closeModal;
}
modalScope.modal.show();
}, function (err) {
deferred.reject(err);
});
return deferred.promise;
}
function _cleanup(scope) {
scope.$destroy();
if (scope.modal) {
scope.modal.remove();
}
}
function _evalController(ctrlName) {
var result = {
isControllerAs: false,
controllerName: '',
propName: ''
};
var fragments = (ctrlName || '').trim().split(/\s+/);
result.isControllerAs = fragments.length === 3 && (fragments[1] || '').toLowerCase() === 'as';
if (result.isControllerAs) {
result.controllerName = fragments[0];
result.propName = fragments[2];
} else {
result.controllerName = ctrlName;
}
return result;
}
} // end
})();
Usage:
appModalService
.show('<templateUrl>', '<controllerName> or <controllerName as ..>', <parameters obj>)
.then(function(result) {
// result from modal controller: $scope.closeModal(result) or <as name here>.closeModal(result) [Only on template]
}, function(err) {
// error
});
You can use another service to centralize the configuration of all modals:
angular.module('app')
.factory('myModals', ['appModalService', function (appModalService){
var service = {
showLogin: showLogin,
showEditUser: showEditUser
};
function showLogin(userInfo){
// return promise resolved by '$scope.closeModal(data)'
// Use:
// myModals.showLogin(userParameters) // get this inject 'parameters' on 'loginModalCtrl'
// .then(function (result) {
// // result from closeModal parameter
// });
return appModalService.show('templates/modals/login.html', 'loginModalCtrl as vm', userInfo)
// or not 'as controller'
// return appModalService.show('templates/modals/login.html', 'loginModalCtrl', userInfo)
}
function showEditUser(address){
// return appModalService....
}
}]);
Create a directive to be used inside the modal and inside the directive you can assign the modal it's own controller and scope. If someone wants some example code I can put something up.
I was looking for a simple way to attach a controller to a modal instance and manage all modals with a single service. Also, I wanted the modal to have it's own isolated child scope. I wasn't satisfied with using ng-controller and I found other answers to be overly complicated to the point where you could easily loose track of scope and end up with circular or unidentifiable dependencies. I created the following service for my purposes.
You can pass an optional parentScope parameter to explicitly assign a parent scope to the created modal scope.
You could easily modify the instantiateModal method to accept $ionicModal options as an argument - I just didn't have the need for it.
BTW - I'm using the Webpack babel-loader for transpilation and the html-loader to load the templates. But, in it's simplest form, it's just a basic service.
/**
* nvModals
* #description A modal manager. Attaches a specified controller to an $ionicModal instance.
*/
import myModalTemplate from '../common/modals/my-modal.html';
import otherModalTemplate from '../common/modals/other-modal.html';
let nvModals = function (
$rootScope,
$controller,
$ionicModal
) {
var _self = this;
_self.methods = {
/**
* Instantiate and show a modal
*/
showMyModal: (parentScope) => {
var parentScope = parentScope || null;
_self.methods.instantiateModal('MyModalController', myModalTemplate, parentScope)
.show();
},
/**
* Instantiate and show another modal
*/
showOtherModal: (parentScope) => {
var parentScope = parentScope || null;
_self.methods.instantiateModal('OtherModalController', otherModalTemplate, parentScope)
.show();
},
/**
* Instantiate a new modal instance
*
* #param {object} controller Controller for your modal
* #param {string} template Template string
* #param {object} parentScope Optional parent scope for the modal scope
* #return {object} Modal instance
*/
instantiateModal: (controller, template, parentScope) => {
var modalScope;
if(parentScope) {
modalScope = $rootScope.$new(false, parentScope);
} else {
modalScope = $rootScope.$new(false);
}
$controller(controller, {
'$scope': modalScope
});
modalScope.modal = $ionicModal.fromTemplate(template, {
scope: modalScope,
animation: 'slide-in-up'
});
modalScope.$on('modal.hidden', (evt) => {
evt.targetScope.$destroy();
if (evt.targetScope.modal) {
evt.targetScope.modal.remove();
}
});
modalScope.hideModal = function () {
modalScope.modal.hide();
};
return modalScope.modal;
}
};
return _self.methods;
};
nvModals.$inject = [
'$rootScope',
'$controller',
'$ionicModal'
];
export default nvModals;
In your controller...
$scope.modals = nvModals;
In the associated template
ng-click="modals.showMyModal()"
In the modal template
ng-click="hideModal()"
Ok, I have seen a lot of different solutions to better handling Ionic modals because of the lack of a controller option or something similar.
After playing with React for a while I came up with another option, more declarative in my opinion. Is in ES6 and just a prototype but you can have an idea:
(function() {
'use strict';
#Inject('$scope', '$ionicModal', '$transclude', '$rootScope')
class Modal {
constructor() {
let { animation, focusFirstInput, backdropClickToClose, hardwareBackButtonClose } = this;
$transclude((clone, scope) => {
let modal = this.createModalAndAppendClone({
scope,
animation,
focusFirstInput,
backdropClickToClose,
hardwareBackButtonClose
}, clone);
this.setupScopeListeners(modal.scope);
this.createIsOpenWatcher();
this.addOnDestroyListener();
this.emitOnSetupEvent(modal.scope);
});
}
setupScopeListeners(scope) {
scope.$on('modal.shown', this.onShown);
scope.$on('modal.hidden', this.onHidden);
scope.$on('modal.removed', this.onRemoved);
}
addOnDestroyListener() {
this.$scope.$on('$destroy', () => {
this.removeModal();
});
}
createIsOpenWatcher() {
this.isOpenWatcher = this.$scope.$watch(() => this.isOpen, () => {
if (this.isOpen) {
this.modal.show();
} else {
this.modal.hide();
}
});
}
emitOnSetupEvent(scope) {
this.onSetup({
$scope: scope,
$removeModal: this.removeModal.bind(this)
});
}
createModalAndAppendClone({
scope = this.$rootScope.$new(true),
animation = 'slide-in-up',
focusFirstInput = false,
backdropClickToClose = true,
hardwareBackButtonClose = true
}, clone) {
let options = {
scope,
animation,
focusFirstInput,
backdropClickToClose,
hardwareBackButtonClose
}
this.modal = this.$ionicModal.fromTemplate('<ion-modal-view></ion-modal-view>', options);
let $modalEl = angular.element(this.modal.modalEl);
$modalEl.append(clone);
return this.modal;
}
removeModal() {
this.modal.remove();
this.isOpenWatcher();
}
}
function modal() {
return {
restrict: 'E',
transclude: true,
scope: {
'onShown': '&',
'onHidden': '&',
'onRemoved': '&',
'onSetup': '&',
'isOpen': '=',
'animation': '#',
'focusFirstInput': '=',
'backdropClickToClose': '=',
'hardwareBackButtonClose': '='
},
controller: Modal,
bindToController: true,
controllerAs: 'vm'
}
}
angular
.module('flight')
.directive('modal', modal);
})();
And then you can use it like this:
<modal is-open="vm.isOpen" on-shown="vm.onShown()" on-hidden="vm.onHidden()" on-removed="vm.onRemoved()" on-setup="vm.onSetup($scope, $removeModal)">
<div class="bar bar-header bar-clear">
<div class="button-header">
<button class="button button-positive button-clear button-icon ion-close-round button-header icon" ng-click="vm.closeModal()"></button>
</div>
</div>
<ion-content class="has-header">
<create-flight-form on-submit="vm.submit()"></create-flight-form>
</ion-content>
</modal>
You open and close the modal with a boolean value bind to is-open and then register callbacks for the different events.

Making a mixin of interfaces in Typescript

I have a class with over 80 methods, and each method accepts an object containing some defined interface.
class Stuff {
/* many more */
getAccount(req: IAccount, callback: ICallback) {
return this._call('getAccount', req, callback);
}
getIds(req: IIDs, callback: ICallback) {
return this._call('getIds', req, callback);
}
/* many more */
}
pretty 'boring' stuff, since it's just mapping to the underlaying _call method and making it type safe for each of the methods.
But sometimes these req param objects are made up from 2 interfaces or more, and instead of creating another interface for each time there's an "awkward", like this:
export interface ILoled extends IAccount {
loled: boolean;
}
export interface IRofloled extends ILoled {
rofled: boolean;
}
class Stuff {
getLols(req: ILoled){
}
getRofls(req: IRofloled){
}
}
is there any way I can just put it as an "inline" mixin of interfaces inside the method parameter list? like (which obviously don't work):
class Stuff {
getMoreStuff(req: <{} extends IAccount, ITime>) {
}
}
Yes you can, as of Typescript 1.6. Called Intersection types, use the & operator to combine types.
function extend<T, U>(first: T, second: U): T & U {
let result = <T & U> {};
for (let id in first) {
result[id] = first[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
result[id] = second[id];
}
}
return result;
}
var x = extend({ a: "hello" }, { b: 42 });
x.a; // works
x.b; // works
is there any way I can just put it as an "inline" mixin of interfaces inside the method parameter list
No. You cannot extend an interface inline