es6 issue while accessing class variables in a $resource.query callback function - javascript

I'm using ES6 with Angular JS 1.X. Whenever I try to access a class-level variable (declared in the constructor) in a $resource.query callback function, I get this error:
"TypeError: Cannot read property 'maxSize' of undefined".
eg:
Constructor:
constructor() {
this.invArr = [];
this.maxSize = 3;
}
Class Method:
bindData(){
this.invArr = this.invLookUpSvc.getPortalInvByProdNbrSum().query({
rtbProductNbr: this.productNumber
}, function (data) {
if (angular.isDefined(data)) {
this.invArr = data; //this.invArr not found
console.log(this.maxSize); //this.MaxSize not found.
}
});
}

The context of this has changed in the callback function for this.invLookUpSvc.getPortalInvByProdNbrSum().query. To resolve this, you should bind the callback function to the this context:
bindData(){
this.invArr = this.invLookUpSvc.getPortalInvByProdNbrSum().query({
rtbProductNbr: this.productNumber
}, function (data) {
if (angular.isDefined(data)) {
this.invArr = data;
console.log(this.maxSize);
}
}.bind(this));
}

Related

VueJS returns undefined in created function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
i have started working on a small project using VueJs, i've made a get request using Axios library which returns some data as expected, but I cannot call loadUsers function using this inside mounted
this is my code:
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then(function(data){
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
as you can see also i've used self variable to call my loadUsers() function, but i'm still getting
this is undefined error
You're referencing this.users within the callback to axios.get().then() in loadUsers(). Due to you're using a standard function and not an arrow function, this is not referring to the Vue instance, i.e. the scope for this is now incorrect. Either use an arrow function or change the reference:
// Do this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then((data) => { // Using an arrow function.
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
// Or this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
let self=this; // Adding "self"
axios.get('/Thirdparty/loadUsers').then(function(data){
self.users = data.data; // Referencing "self" instead of "this".
});
}
},
created(){
let self=this
self.loadUsers();
}
}

Is it possible to modify defined getter function?

Working on a performance reviewing tool on wechat mini apps platform (javascript + native hybrid based on wechat app), I am trying to inject codes into its prototypes, for example the wx.request function.
This is how you would use a wx.request function:
wx.request({
url: 'test.php',
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})
So in order to know how long the request has taken without manually writing adding all the anchors, I tried to inject code by:
var owxrequest = wx.request
wx.request = function() {
console.log('test', Date.now())
return owxrequest.apply(owxrequest, arguments)
}
This failed and I got an Cannot set property "prop" of #<Object> which has only a getter error.
So I realized the the object must have been defined similar to:
wx = {
request: get function(){
...
}
...
}
So I tried:
var owxrequest = wx.request
Object.defineProperty(wx, 'request', {
get: function() {
console.log('test', Date.now())
return owxrequest.apply(owxrequest, arguments)
}
})
This failed with an error (request: fail parameter error: parameter.url should be String instead of Undefined). Then I tried:
var owxrequest = wx.request
Object.defineProperty(wx, 'request', {
set: function() {
console.log('test', Date.now())
return owxrequest.apply(owxrequest, arguments)
}
})
This wouldn't throw an error but it also has no effect when calling wx.request()...
You can implement this by re-define the getter. The point is: the re-defined getter should return a function object, as wx.request is a function:
Object.defineProperty(wx, 'request', {
get: function() {
return function() {
//...
};
}
});
Why I get the error: request: fail parameter error: parameter.url should be String instead of Undefined?
You are trying to access the arguments of the getter itself (the arguments of function in get: function(){...}). This arguments is an empty object and it can be verified by console.log() statement. As it is empty, arguments.url is undefined, that's why wx complains about the parameter.
Here is an working example:
let wx = {
get request(){
return function() {
console.log(10);
return 88;
};
}
};
let oldF = wx.request;
Object.defineProperty(wx, 'request', {
get: function() {
return function() {
console.log(new Date());
return oldF.apply(wx, arguments);
};
}
});
console.log(wx.request());
The above code would print:
2017-08-28T06:14:15.583Z // timestamp
10
88
You could just shadowing the request function.
Simple example:
Shadowing the getter:
// original getter latest
let base = {
num: 1,
get latest() {
return this.num;
}
}
console.log(base.latest);
// shadowing getter latest
Object.defineProperty(base, 'latest', {
get: function() {
return this.num + 1;
}
});
console.log(base.latest);
Simple shadowing a object property
// your original object
let base = {
request(){
console.log('request original');
}
};
base.request()
base.request = () => {
console.log('request new implementation');
};
// now shadow the original request implementation
base.request()

Return function in object not working

I'm trying to return an object with a function inside. When I call it, I get an error:
Uncaught TypeError: config.something is not a function
What am I doing wrong, and how can I fix it?
JSFiddle
function config() {
function something() {
console.log('something');
}
return {
something: something
};
}
config.something();
Description
Since config is a function not an object you need to call/execute it, this then returns the object that you can call .something on.
Code for Function
function config() {
function something() {
console.log('something');
}
return {
something: something
};
}
config().something();
Code for Object
var config = {
something: function() {
console.log('something');
}
};
config.something();
More resources:
https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e#.eqdstb1l6
Object vs Class vs Function
https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e#.eqdstb1l6
https://www.google.com/search?q=javascript+functions+vs+objects&oq=javascript+functions+vs+&aqs=chrome.0.0j69i57j0l4.4688j1j7&sourceid=chrome&ie=UTF-8

Console logging "this" returns "null"

I am trying to create a flux store for a React app I am building. I am using an object-assign polyfill npm package and Facebook's Flux library.
Initially I was getting the error "Cannot read property '_data' of null' error in the console which was refering to var currIds = this._data.map(function(m){return m.id;});. That method is currently the only one being called directly. I then did console.log(this) which returned "null".
I find this strange. What is going on?
My code:
var Assign = require('object-assign');
var EventEmitterProto = require('events').EventEmitter.prototype;
var CHANGE_EVENT = 'CHANGE';
var StoreMethods = {
init: function() {},
set: function (arr) {
console.log(this);
var currIds = this._data.map(function(m){return m.id;});
arr.filter(function (item){
return currIds.indexOf(item.id) === -1;
}).forEach(this.add.bind(this));
},
add: function(item){
console.log(this);
this._data.push(item);
},
all: function() {
return this._data;
},
get: function(id){
return this._data.filter(function(item){
return item.cid === id;
})[0];
},
addChangeListener: function(fn) {
this.on(CHANGE_EVENT, fn);
},
removeChangeListener: function(fn) {
this.removeListener(CHANGE_EVENT, fn);
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
bind: function(actionType, actionFn) {
if(this.actions[actionType]){
this.actions[actionType].push(actionFn);
} else {
this.actions[actionType] = [actionFn];
}
}
};
exports.extend = function(methods) {
var store = {
_data: [],
actions: {}
};
Assign(store, EventEmitterProto, StoreMethods, methods);
store.init();
require('../dispatcher').register(function(action){
if(store.actions[action.actionType]){
store.actions[action.actionType].forEach(function(fn){
fn.call(null, action.data);
})
}
});
return store;
};
I can't see where set is called, however your this can be null if the function is invoked through call (see here) or apply, and your first argument is null.
This also happens in your require.register callback:
fn.call(null, action.data) //First parameter is your 'this'.

Should my factory return an object with helper methods or should I use prototype?

I'm a beginner with angular and I try to understand if I should user a factory like that:
app.factory('FoobarServices', ['$http', function ($http) {
var Foobar = {
// Model
};
return {
getFoobar: function () {
},
setFoobar: function (Foobar) {
},
update: function (foobar) {
},
delete: function (id)
}
};
}]);
Or something like:
app.factory('Fooba', ['$http', function($http) {
function Foobar(foobar) {
// Initialize foobar
};
Foobar.prototype = {
getFoobars: function() {
},
setFoobar: function(foobar) {
},
update: function(foobar) {
},
delete: function(id) {
},
};
return Foobar;
}]);
I'm not sure to understand what's the pros and cons of each pattern, and which one is more suitable for an angular project.
Could you please tell me which one should I use?
It depends on how you want to use your service.
Factory is usually being used to store some constructor from which you can later instantiate some objects.
For example:
app.factory('Client', function () {
function Client (name) {
this.name = name;
}
Client.prototype.sayHello = function () {
console.log('Hello, my name is ' + this.name + '!');
}
return Client;
})
.controller('ClientController', function (Client) {
var bob = new Client('Bob');
})
If your service is singleton, you can register it as service instead of factory and angular will create an instance for you.
Or you can register it as factory but return some object with methods. It is useful when you don't want to deal with context (this) inside your service logic:
app.factory('ClientStorage', function () {
function set () {
// to be implemented
}
function get () {
// to be implemented
}
return {
get: get,
set: set
};
})

Categories