In extjs MVC architecture how to pass parameter to function - extjs

I want to pass parameter "aaa" to disableFlied function, but the code below didn't work:
init: function() {
this.control({
'#speedCheck': {
change :this.disableFlied("aaa")
}
});
},
disableFlied: function(cmpName){
var a = Ext.getCmp(cmpName);
a.setDisabled(!a.isDisabled());
}
How to pass "aaa" to disableFlied function?

You must pass a function as event handler, here you're passing the result of calling disableField yourself (i.e. nothing since this method doesn't return anything). What you need to do is create another function that passes the desired parameter. In Ext, you can do that with the Ext.bind function.
Here's how you should use it:
this.control({
'#speedCheck': {
change: Ext.bind(this.disableField, this, ['aaa'])
}
});
This will create a closure around the disableField method. This
is equivalent to this vanilla javascript code:
'#speedCheck': {
// This is the default scope, but I prefer to make it
// explicit that the handler must be called in the
// current scope
scope: this
,change: function() {
// When this function is called, it will call
// disableField with the desired parameter
this.disableField('aaa');
}
}

Related

Use value returned by one function in another function

I am new to backbone and sugarcrm. Can anyone please explain how to use the value returned by one function in another function?
This is the pseudo code :
({
extendsFrom: 'RecordView',
initialize: function(options) {
this._super('initialize', [options]);
this.context.on('button:get_tax:click', this.get_tax, this);
this.model.addValidationTask('addressValidation',_.bind(this.save_button, this));
},
save_button: function(fields, errors, callback) {
use the value of 'currentTax' variable
},
get_tax: function() {
var currentTax = this.model.get('taxrate_name');
return currentTax;
}
})
Thank you
save_button: function(fields, errors, callback) {
var curTax = this.get_tax();
},
Explanation:
get_tax is a function that you have defined within the ({...}) object.
Backbone calls the initialize function with that object being accessible via this.
By using _.bind(this.save_button, this) (in initialize) you are binding the this object to the save_button function, meaning that it will also be available as this within your function when called.
Therefore you can access the same object with this in that function and just call the object's function and retrieve the value.

Why does my function need parentheses?

In my framework, the functions are called without parentheses.... (See showErrors)
(function () {
'use strict';
angular
.module('core')
.directive('showErrors', showErrors);
showErrors.$inject = ['$timeout', '$interpolate'];
function showErrors($timeout, $interpolate) {
var directive = {
restrict: 'A',
require: '^form',
compile: compile
};
return directive;
I get how it works... but when I try this, my component won't work. It only works if I change it to .component('hotkeys', HotkeysComponent()); // adding parenthesis to HotkeysComponent
angular
.module('contacts.components')
.component('hotkeys', HotkeysComponent);
function HotkeysComponent() {
var component = {
templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
controller: 'AddManagerController',
controllerAs: 'vm'
};
return component;
To clarify, it won't work unless I do HotkeysComponent()
angular
.module('contacts.components')
.component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?
Components can be registered using the .component() method of an AngularJS module (returned by angular.module()). The method takes two arguments:
The name of the Component (as string).
The Component config object. (Note that, unlike the .directive()
method, this method does not take a factory function.)
As per your question, the second argument must be an object and that happens only when you called the function(second argument)
Components in angular js
read this for more info
There is a big difference between the two. HotkeysComponent as a parameter gives the function pointer, while HotkeysComponent() is the value HotkeysComponent returns.
An example:
testFunction(variable) {
variable();
}
testFunction(alert);
Here we pass alert as a function (not the return value). Now we can execute this function inside testFunction.
testFunction(variable) {
console.log(variable);
}
sum(x, y) {
return x + y;
}
testFunction(sum(10,20));
Here we pass the outcome of the sum function to the function, which we can use inside our testFunction.

angularJS: Function in function

Hello I'm new in angularJS. Suitable or not to implement function inside function?
For example like this:-
$scope.loadDistrict = function(id) {
// statement
$scope.loadBasedOnYear = function(y_id) {
console.log(y_id);
// statement
};
};
If you bind method on scope, it's available from view.
From your code
$scope.loadDistrict = function(id) {
// statement
$scope.loadBasedOnYear = function(y_id) {
console.log(y_id);
// statement
};
};
loadBasedOnYear won't available until loadDistrict is called.
It's very bad pattern to follow.
It is possible but without context I don't really know why you would do this, calling $scope.loadBasedOnYear before calling $scope.loadDistrict will result in an error so be careful with such a design pattern.
Yes this is fine.
You should watch out for when the function will be executed outside of angular's cycle. E.g. if you do:
setTimeout(function() { $scope.test = 5; }, 1000);
If you need to do this then you need to wrap the function in $scope.$apply(), or use $timeout.

Angular JS Factory Clarification

what is the difference between all these Factory definitions
app.factory('myFirstFactory', function () {
var customShow = function () {
return "My First Factory";
}
return customShow;
});
app.factory('mySecondFactory', function () {
return {
show: function () {
return "My Second Factory";
}
}
});
app.factory('myThirdFactory', function () {
function myCustomShow() {
return "My Third Factory";
}
return {
show: myCustomShow
}
});
Here is how its been called in the controller. What is the ideal case of defining the factory. What is the actual return type from the factory, In one defintion, it could seems like Factory and Service are look alike. Can someone please clarify
$scope.message1 = myFirstFactory();
$scope.message2 = myService.show();
$scope.message3 = mySecondFactory.show();
$scope.message4 = myThirdFactory.show();
The first one returns customShow. customShowis declared as a function. So the service returned by this factory is a function. So, when you inject myFirstFactoryin a controller or another service, the injected value will be a function. BTW, you shouldn't choose xxxFactoryas the name. The component you're defining, thanks to a factory, is a service, not a factory. What is injected is the returned service, not its factory.
The second one and the thirst one both return an object:
return {
show: ...
}
So what will be injected in both cases is an object, and not a function like in the first case.
The returned object has a single field named show, which is a function. The second one defines a named function, and assigns this named function to the showproperty of the returned object, whereas the third one directly assigns an anonymous function to the showproperty of the returned object. But the end result is the same. The only difference you'll see is when printing (for debugging) the function itself:
console.log(theService.show);
will print
function myCustomShow() { ... }
for the second one, but will print
function () { ... }
for the third one.
It's all about your preference how to handle the interface of the factory. Another point is best practice. The third one is suggested by John Papa in his detailed angular-styleguide even though he puts the the interface at the top and not below all functions due to readability. It's actually derived by the Revealing Module Pattern.
The first remindes me of a class definiton if there is only a single function returned by the factory. Thus it has to be invoked when you inject it into your controller as follows:
function MyController($scope, myFirstFactory)
{
// $scope.myFirstFactory would print out "My First Factory"
$scope.myFirstFactory = myFirstFactory();
}
This is usually used if you plan to write object-oriented AngularJS services, since factories are useful to define a classes that you can instantiate many times using the new keyword, while services always create singletons.
app.factory('MyFirstFactory', function() {
var privateVariable = 'foo';
// Constructor
var MyFirstFactory = function(bar) {
this.bar = bar;
};
MyFirstFactory.prototype.showCustom = function() {
return "My Third Factory";
};
return MyFirstFactory;
});
You could then create many instances like so:
function MyController($scope, myFirstFactory)
{
// $scope.myFirstFactory would print out "My First Factory"
$scope.myFirstFactory = new MyFirstFactory();
$scope.showCustom = myFirstFactory.showCustom();
}
The second is a variation of the third one which both return an object as #jb-nizet mentioned.

Custom events firing

I have a question, which I'm not sure how to put, but I will try.
I made custom element, called matrix, it has rows and columns. I can select a row and/or column. Now I want, from inside my element, to fire set events: onRowSelect, onColumnSelect, onCellSelect, and pass parameters to any listeners these events might have.
For example:
<matrix
data-on-row-select='onRowSelect'
data-on-cell-select='foo'>
</matrix>
var controller = function($scope) {
$scope.onRowSelect = function(a, b, c) { };
$scope.foo = function(a, b, c) { };
/* ... */
}
How should I declare scope of matrix directive? How can I fire these events?
You simply bind onRowSelect to directive's scope using two-way binding:
.directive('matrix', function() {
return {
scope: {
onRowSelect: '='
},
link: function($scope) {
function onRowSelect() {
if (angular.isFunction($scope.onRowSelect)) {
$scope.onRowSelect(a, b, c);
}
}
}
}
})
AngularJS only supports binding to specific events (like click). If you want to subscribe to custom events you need to write your own directive. But you can use the Event Binder directive from the Angular UI library http://angular-ui.github.io/ui-utils/#/event
A little abstract example of how you could do it (I'd recommend you use the answer suggested by #package though (as it's a wee bit cleaner, in my opinion)).
With my solution, we loop through the passed in arguments and if the property key begins with on, we stow it away in an array.
We then loop through the array and setup event listeners for each of the keys in said array, and execute the passed in callback.
controller('ctrl', function ($scope) {
$scope.onRowSelect = fn();
$scope.onCellSelect = fn();
}
// HTML
<matrix on-row-select="onRowSelect()" on-cell-select="onCellSelect()"></matrix>
directive('matrix', function () {
return {
link: function (scope, el, attrs) {
var events = Object.keys(attrs).map(function (prop) {
if (prop.match(/^on/)) {
return prop;
}
});
events.forEach(function (event) {
if (!!event) {
scope.$on(event, scope.$eval(attrs[event]));
}
});
}
}
}
Whenever the corresponding event reaches the scope of matrix, it's callback will be executed in the context of the matrix scope.
JsBin: http://jsbin.com/lasajimi/1/edit
Edit: I am by no means 'skilled' when it comes to regex, but it seems to have caught on to the correct properties when I tested it out. Hopefully someone can correct me here if it's way off.

Resources