Extending objects in angularjs - javascript

I'm fairly new to angularjs. I'm looking for a way to return objects for extending from a factory that ARE NOT singletons. This way, people can't muck with the object data higher up in the application stack. This is what I've come up with so far, is it correct? Or is there a better way?
angular.module('utils', [])
.factory('extendableOject', function () {
return function () {
return {
prop1 : 1,
func1 : function () {
this.prop1++;
}
};
} ();
});

Ok, I figured it out:
angular.module('utils', [])
.factory('extendableOject', function () {
return function () {
return {
prop1 : 1,
func1 : function () {
this.prop1++;
}
};
};
});
I should not have been invoking the function from within the factory. That would have been no different than just returning the object itself. With the above code, I can call "extendableObject()" from anywhere to retrieve a fresh instance.

Related

How to call another function inside function in export default?

export default {
one: () => {
//some codes
},
two: () => {
//some codes
one(); // error
this.one(); // error
}
}
I have module like that, and I want to call function one() inside function two().
But I got error like this : TypeError: Cannot read property 'one' of undefined.
How can I fix it? I want to know the cause.
What about extracting them out into separate functions and then include them in the export?
const one = () => {
//some codes
};
const two = () => {
//some codes
one();
};
export default {
one,
two
}
You shouldn´t use arrows function if you want to give a new context to the this keyword.
Look this example, it uses an arrow function in the two method. It would return error since the this keyword is not related to the object, but mantains the context from the last function.
let obj = {
one: function() {
console.log("one");
},
two: () => { // Arrow function
this.one();
}
}
obj.two();
If you use a normal function, the this keyword would be related to the object:
let obj = {
one: function() {
console.log("one");
},
two: function() { // Normal function
this.one();
}
}
obj.two();
This is the main difference between arrow functions and normal functions

Vuejs ajax call not mapping changes to underlying html table

I am making simple ajax call with vuejs and axios:
var app1 = new Vue({
el: '#app1',
data: {
test: []
},
methods: {
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
}
});
Why is this working:
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
But this is not working, changes are not mapped into table (this.test is undefined):
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(function(response){this.test = response.data.listBACAET});
}
This is because of the way arrow functions work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
When using an arrow function, this is implicitly bound to this of the enclosing scope, which is, in your case, the vue instance on which the method is called.
So you're setting the data of your view model, which works.
When using a std. function, there is no this in the scope, hence the error. To use a std. function, you need to define a closure for your view model like this:
setAJAX: function () {
let vm = this
axios.get('...').then( function(response) {
vm.test = response.data.listBACAET
});
}

What is the correct way to write chainable function in Angular?

I try to write custom function for my Angular app.
I have followed official guide and create an independent library.
I intent to write chainable function like this
var obj = {
test : function(){
console.log('1');
return this;
},
test2 : function(){
console.log('2');
return this;
}
}
obj.test().test2();
How to export and import a chainable method in Angular? And which is the correct file type that I should write this custom function? For example, might be service, model, or component?
Thank you
How to export and import a chainable method in Angular
If you care about inferred type safety use a class:
class Obj {
test() {
console.log(1);
return this;
}
test2() {
console.log(2);
return this;
}
}
new Obj().test().test2();
And which is the correct file type that I should write this custom function? For example, might be service, model, or component?
In any .ts file. Simply export e.g.:
export const obj = new Obj();
Library: Underscore.js
If you're willing to use a (small) library, Underscore.js provides a chain() methods that lets you chain calls together and return the result. To use or add a custom function, you could create a mixin which is basically your own custom underscore function.
As an example - take some JSON, map it, and apply a custom function to the items then show something:
example code
_.mixin({
test_logging: function(stuff) {
console.log(" * test()!");
console.log({'stuff': stuff});
return stuff;
},
test_message: function(stuff) {
return JSON.stringify(stuff);
}
});
var results = _.chain(data)
.map(function(user) {
return {
'name': user.name,
'email': user.email,
'company': user.company
};
})
.test_logging()
.test_message()
.value();
JSFiddle Link

Testing a method of an object returned by a function

I have a function that returns an object with many methods and I need to check one of the methods inside this returned object. I am using AngularJS and Karma+Jasmine as testing suite. How do I call methods inside the object returned by a function?
function modalOptions() {
.........
return this.$q((resolve) => {
// test accessable here
this.solveModel = {
save: () => {
// test can't call save()
this.saveToDB = this.toSendToDB;
},
cancel: () => { ...
},
delete: () => { ...
}
};
});
}
My test is somewhat like this...
it('should save modal with the data', function() {
scope.$apply();
expect(vm.modalOptions).toBeDefined();
vm.toSendToDB = true; // hard-coded
vm.savedToDB = undefined // default value from other controller
spyOn(vm, 'modalOptions').and.callThrough();
console.log(vm.modalOptions()); // gives weird response: c{$$state: Object{status: 0}} instead of the solveModal object
expect(vm.toSendToDB).toBeTruthy();
expect(vm.savedToDB).toBeTruthy();
});
Sorry, I can not comment yet, but the promise has to be resolved and the solveModel passed to it, in order for solveModel to be returned. Where do you resolve the promise?

RequireJS and Prototypal Inheritance

I'm running into an issue with using RequireJS and Prototypal inheritance. Here's my module:
define(function () {
function Module(data) {
this.data = data;
}
Module.prototype.getData = function () {
return this.data;
};
Module.prototype.doSomething = function () {
console.log(this.data);
console.log(this.getData());
};
return Module;
Module.prototype.callFunction = function (fn) {
if (this[fn]) {
console.log('call');
Module.prototype[fn]();
}
};
});
Then I instantiate the module, like so:
var module = new Module({ name: 'Marty' });
module.getData(); // returns { name: 'Marty' }
module.data; // returns { name: 'Marty' }
module.callFunction('doSomething') // returns undefined on the first (and second) console log
The console.logs in the module.doSomething() always return undefined. Am I misunderstanding how prototypal inheritance works with RequireJS?
As it turns out, I had written the callFunction method incorrectly. The correct way is:
Module.prototype.callFunction = function (fn) {
if (this[fn] && typeof this[fn] === "function") {
this[fn]();
}
};
The problem was using Module.prototype instead of this. Whoops.

Categories

Resources