Use value returned by one function in another function - backbone.js

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.

Related

AngularJS 1.6.9 controller variable bound to service variable doesn't change

I have 2 components which are both accessing a service. One component delivers an object and the other one is supposed to display it or just receive it. The problem is that after the initialization process is finished the variable in the display component doesn't change.
I have tried using $scope , $scope.$apply(), this.$onChanges aswell as $scope.$watch to keep track of the variable, but it always stays the same.
This controller from the display component provides a text, which is from an input field, in an object.
app.controller("Test2Controller", function ($log, TestService) {
this.click = function () {
let that = this;
TestService.changeText({"text": that.text});
}
});
That is the the service, which gets the objekt and saves it into this.currentText.
app.service("TestService", function ($log) {
this.currentText = {};
this.changeText = function (obj) {
this.currentText = obj;
$log.debug(this.currentText);
};
this.getCurrentText = function () {
return this.currentText;
};
});
This is the controller which is supposed to then display the object, but even fails to update the this.text variable.
app.controller("TestController", function (TestService, $timeout, $log) {
let that = this;
this.$onInit = function () {
this.text = TestService.getCurrentText();
//debugging
this.update();
};
//debugging
this.update = function() {
$timeout(function () {
$log.debug(that.text);
that.update();
}, 1000);
}
//debugging
this.$onChanges = function (obj) {
$log.debug(obj);
}
});
I spent quite some time searching for an answer, but most are related to directives or didn't work in my case, such as one solution to put the object into another object. I figured that I could use $broadcast and $on but I have heard to avoid using it. The angular version I am using is: 1.6.9
I see a problem with your approach. You're trying to share the single reference of an object. You want to share object reference once and want to reflect it wherever it has been used. But as per changeText method, you're setting up new reference to currentText service property which is wrong.
Rather I'd suggest you just use single reference of an object throughout and it will take care of sharing object between multiple controllers.
Service
app.service("TestService", function ($log) {
var currentText = {}; // private variable
// Passing text property explicitly, and changing that property only
this.changeText = function (text) {
currentText.text = text; // updating property, not changing reference of an object
$log.debug(currentText);
};
this.getCurrentText = function () {
return currentText;
};
});
Now from changeText method just pass on text that needs to be changed to, not an new object.

How to pass variables within controllers in AngularJS

Hi I need to use a variable from the result scope of one controller to another controller. I can achieve this by using nested controller but in my case my controller 2 is not a child of controller 1. I somehow able to achieve my output with the following controller but still i want to know is this best practice if not how can i pass variables between various controllers.
angular.module('test',[])
.factory('PassParameter', PassParameter)
function PassParameter(){
var thisValue = {};
return {
getParameter: function () {
return thisValue;
},
setParameter: function (setValue) {
_.extend(thisValue, setValue);
},
removeParameter : function(value) {
_.omit(thisValue, value);
}
};
};
i Pass an object to setParameter function and get by its value from getParameter function.
this is the way that I'm passing info between controllers.
*Note that I'm using angular.copy so I won't lose reference, this way when "obj" is changed, you don't need to get it again.(works only on objects {})
angular.module('test').service('mySrv',
function () {
var obj = {};
this.getObj = function(){
return obj;
};
this.setObj = function(obj){
obj = angular.copy(obj);
};
});

How to create any kind of immutable providers in AngularJS

Consider the following example:
angular.module('demo')
.service('MyService', function () {
this.fn = function () {
console.log('MyService:fn');
};
})
.factory('MyFactory', function () {
function fn() {
console.log('MyFactory:fn');
}
return { fn: fn };
})
.value('MyValue', {
fn: function () {
console.log('MyValue:fn');
}
})
.constant('MyConstant', {
fn: function () {
console.log('MyConstant:fn');
}
})
.run(function (MyService, MyFactory, MyValue, MyConstant) {
MyService.fn();
MyFactory.fn();
MyValue.fn();
MyConstant.fn();
MyService.fn = undefined;
MyFactory.fn = undefined;
MyValue.fn = undefined;
MyConstant.fn = undefined;
})
.run(function (MyService, MyFactory, MyValue, MyConstant) {
MyService.fn();
MyFactory.fn();
MyValue.fn();
MyConstant.fn();
});
When the first run() is executed, all 4 console logs will be executed and print something on the console. Then I set each of the providers fn function to undefined for simplification purposes, say someone rewrote this function somewhere (which is something I want to prevent).
On the second run() block, everything is undefined and errors will be thrown. I'm confused by this... Shouldn't at least some of them (constant is the first to come to mind) be immutable objects?
Is this the expected behavior or am I doing something wrong?
Why is this a surprise. Angular is a framework running on top of Javascript, and Javascript is a dynamic language. Your question is really about the language construct.
First, recognize that all the calls are, at the end of the day, registering a provider that would return an object to be injected. .service, .factory, and .value are just short hands for .provider (.constant is a bit different).
Having established that there is no difference between them once the object is injected, all you then need to concern yourself with is how to make that object immutable.
Javascript provides Object.freeze function, so for example, you could do:
var immutable = {
fn: function () {
console.log('MyConstant:fn');
}
};
Object.freeze(immutable);
app.constant("MyConstant", immutable);
The functions constant, factory, service etc. allow you to create Javascript objects that are created once, then cached by angular, and injected into components as/when needed. Because these are Javascript objects, then (ignoring the possibility of using freeze) any bit of code has access to these objects can modify properties on them, as you have demonstrated.
Although properties on the objects themselves can be modified, the object itself can't be changed to another one, so if you really want an immutable provider, that is safe from all tampering, one way that I can think of is to use a factory that returns not an object, but a getter function:
app.factory('MyFactory', function() {
var functions = {
myFunctionName: function() {
}
};
return function(functionName) {
return functions[functionName];
};
});
which can be used, say in a controller, as
app.controller('MyController', function(MyFactory) {
MyFactory('myFunctionName')();
});
A drawback of using this over the more traditional way of exposing all the methods and allowing the possibility of the object to be modified is that I suspect unit testing could be more complicated: you wouldn't be able to easily create spies on your factory methods by using createSpy(MyFactory, 'myFunctionName').

In extjs MVC architecture how to pass parameter to function

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');
}
}

Unable to access global variable entire one controller in sencha

I have been trying to access global value inside one controller, but could not access it. i have been following this How to define global variable in sencha but could not set and access global values.
in Controller
config: {
successMessage:100,
control: {
'submitnewword': {
activate: 'onActivate',
itemtap: 'onItemTap',
ConfirmTestCommand:'Confirm'
},
.......
},
onSearchKeyUp: function(searchField) {
success: function (response) {
this.setSuccessMessage(1);
}
else {
this.setSuccessMessage(0);
}
}
and access it
Confirm: function () {
console.log("Confirm----- Caling on Controller");
var testing=this.getSuccessMessage();
console.log("Confirm----- value--"+testing);
},
I dont know, what is the wrong with my code.
I am getting this on console:
Uncaught TypeError: Object [object global] has no method
'setSuccessMessage'
The problem is about scope and you can solve it by:
In your controller init method
init : function() {
me = this;
}
Now access the methods using
me.setSuccessMessage(1)
me.getSuccessMessage();
I think you ran onto the scope visibility issue... I'm not sure where an exception is emitted, from onSearchKeyUp() or from Confirm(). But guess inside it this points not to the controller instance. To help you more you need share more info (sources)
The success function inside onSearchKeyUp has a different scope when it is called. So, inside it, this is not your controller where the successMessage (and of course, its getter and setter) is defined.
A solution is to "bind" the success function to the controller scope using:
success: Ext.bind(function (response) {
this.setSuccessMessage(1);
}, this);

Resources