How can I get the YUI3 sendRequest applied to a Datasource to return predefined objects, instead of plain ones?
For example, I have this Base class with its methods:
function Student(id, name){
this.id = id;
this.name = name;
}
Context.prototype.setId = function(id){ this.id = id; };
Context.prototype.setName = function(name){ this.name = name; };
Context.prototype.getId = function(){ return this.id; };
Context.prototype.getName = function(){ return this.name; };
And I have this code that retrieves data from an API, normalizes it and returns data as objects:
var studApiDataSource = new Y.DataSource.Get({source: API_URL});
studApiDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "response.student",
resultFields: ["id","name"]
}
});
var myCallback = function(e) {
Y.Array.each(e.response.results, function(stud){
Y.log(stud.id+' '+stud.name);
}
}
studApiDataSource.sendRequest({
request: "?cmd=getStudents",
callback: {
success: myCallback,
failure: function (e) { }
}
});
The array of objects retrieved by studApiDataSource.sendRequest() and passed to myCallback are normal objects, with id and name properties. However, I want these to be Student objects, with their member functions too (getId, getName etc)
I'm not sure I fully understand, but you could do something like the following.
var studentJSON = "{\"id\": 17, \"name\":\"my name is\"}";
function Student(obj){
this.name = obj.name;
this.id = obj.id;
}
Student.prototype.setId = function(id){ this.id = id; };
Student.prototype.setName = function(name){ this.name = name; };
Student.prototype.getId = function(){ return this.id; };
Student.prototype.getName = function(){ return this.name; };
YUI().use('json-parse', 'json-stringify', function (Y) {
try {
var stud = new Student(Y.JSON.parse(studentJSON));
alert(stud.getId());
}
catch (e) {
alert(e);
}
});
Related
I want to create a dependent property on my javascript object.
I have an object like in the code snippet. I want to update isPawn property; when isNew property changes.
Is there a way for do something similar that automatically;
if(isNew){
isPawn = true;
}
But they are not have to be same. isNew can be 'false', when isPawn is 'true'
My Object:
var Soldier = function (id,name) {
this.id = id;
this.name = name;
this.isPawn = false;
this.isNew = false;
}
Yes, you can do this using a setter, here is an example:
class Soldier {
#isNew = false;
constructor(id,name) {
this.id = id;
this.name = name;
this.isPawn = false;
}
set isNew(val) {
this.#isNew = val;
this.isPawn = val;
}
get isNew() {
return this.#isNew;
}
}
const soldier = new Soldier();
soldier.isNew = true;
console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn);
soldier.isNew = false;
console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn);
soldier.isPawn = true;
console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn);
#isNew is a private field in this case I'm using it to keep track of what the value of isNew should be (what the getter should return).
Here is an example using a function instead of a class:
var Soldier = function(id, name) {
this.id = id;
this.name = name;
this.isPawn = false;
this.isNewPriv = false;
Object.defineProperty(this, 'isNew', {
set: function(val) {
this.isNewPriv = val;
this.isPawn = val;
},
get: function() {
return this.isNewPriv
}
});
}
var soldier = new Soldier(1, 'none');
soldier.isNew = true;
console.log("isNew:", soldier.isNew, "isPawn:", soldier.isPawn);
soldier.isNew = false;
console.log("isNew:", soldier.isNew, "isPawn:", soldier.isPawn);
soldier.isPawn = true;
console.log("isNew:", soldier.isNew, "isPawn:", soldier.isPawn);
Make a class and instantiate as needed
class Soldier {
constructor(id, name, isNew) {
this.id = id;
this.name = name;
this.isPawn = isNew? true : {something : "whaterverElse"};
this.isNew = isNew;
}
DoSomething(){
this.isNew = false;
}
}
var soldier = new Soldier(1, 'Tim', true);
console.log(soldier);
function somethingElseHappened(){
soldier.DoSomething();
}
somethingElseHappened();
console.log(soldier);
you can make a default values for this properties like this:
var Soldier = function (id,name,isPawn = false,isNew = false) {
this.id = id;
this.name = name;
this.isPawn = isPawn;
this.isNew = isNew;
}
and if you want to change there values to any object for you just do like this:
var newSolider = new Solider(1,"foo",false,true);
I've got two object prototypes like this:
function Tag(name, description) {
this.name = name;
this.description = description || null;
}
function Category(name, description) {
this.name = name;
this.description = description || null;
}
Both of them are exactly the same, which seems awkward. Is it possible to merge them both into an object named 'Entity', and refer to them both by different names (the original 'Tag' and 'Category')?
This may be further complicated by the fact I need to refer to the current prototype name inside the prototype.
Tag.prototype.toJSON = function() {
return {
__type: 'Tag',
name: this.name,
description: this.description
};
};
How can I apply the same 'toJSON' extension to the 'Entity' object, but make sure it returns 'Tag' or 'Category' in the '__type' field, dependent on which object is being used?
I would do something like this:
Dummy = function () {};
Entity = function (name) {
this.name = name;
};
Entity.prototype.toString = function () {
return "My name is " + this.name + ".";
};
A = function () {
Entity.call(this, 'A');
};
Dummy.prototype = Entity.prototype;
Dummy.prototype.constructor = A;
A.prototype = new Dummy();
B = function () {
Entity.call(this, 'B');
};
Dummy.prototype = Entity.prototype;
Dummy.prototype.constructor = B;
B.prototype = new Dummy();
document.body.innerHTML = ""
+ (new A()) + "<br />"
+ (new B());
Here is a small function to make things cleaner (hopefully):
function Nothing () {};
function extend (Sup, proto) {
function Class () {
if (this.init) {
this.init.apply(this, arguments);
}
}
Nothing.prototype = Sup.prototype;
Nothing.prototype.constructor = Sup;
Class.prototype = new Nothing();
delete Nothing.prototype;
for (var k in proto) {
Class.prototype[k] = proto[k];
}
return Class;
}
Here is how to use it:
Entity = extend(Nothing, {
init: function (name) {
this.name = name;
},
toString: function () {
return "My name is " + this.name + ".";
}
});
A = extend(Entity, {
init: function () {
var sup = Entity.prototype;
sup.init.call(this, 'A');
}
});
B = extend(Entity, {
init: function () {
var sup = Entity.prototype;
sup.init.call(this, 'B');
}
});
I'm working on making performance updates on my javascript code.
In Firefox I got this warning:
mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create
I wrote some scripts to prove this, and the results are great: without mutation a simple script runs 66% faster.
But I have trouble converting my code without mutation, I can't write the getters:
This is what I have now:
// Class
function FooBar(options) {
this.options = options;
}
// Prototype
FooBar.prototype = {
// Getters
get a() {
return this.options.a;
},
get b() {
return this.options.b;
},
get ab() {
return this.options.a + this.options.b;
},
// Methods
displayOptions: function() {
console.log(this.options);
}
};
// Code
var options = {
a: 'foo',
b: 'bar'
};
var fooBar = new FooBar(options);
console.log(fooBar.a);
console.log(fooBar.b);
console.log(fooBar.ab);
fooBar.displayOptions();
The getters as a prototype using the this keyword in their return are the problem.
If I use Object.defineProperty the this keyword is wrong, unless I do it inside the constructor, but it would recreate the property on each instance of the class and slow my code down even further.
This works (I just messed up the syntax in my previous attempt):
// Class
function FooBar (options) {
this.options = options;
}
//Prototype getters
Object.defineProperty(FooBar.prototype, 'a', {
get: function() {
return this.options.a;
}
});
Object.defineProperty(FooBar.prototype, 'b', {
get: function() {
return this.options.b;
}
});
Object.defineProperty(FooBar.prototype, 'ab', {
get: function() {
return this.options.a + this.options.b;
}
});
// Methods
FooBar.prototype.displayOptions = function() {
console.log(this.options);
};
// Code
var options = {
a:'foo',
b:'bar'
};
var fooBar = new FooBar (options);
console.log(fooBar.a);
console.log(fooBar.b);
console.log(fooBar.ab);
fooBar.displayOptions();
For those who are curious about the benefits of converting scripts like this to run faster: Run following code and look to your output in the console (Chrome - 66% faster, Firefox - no difference (curious, since I got the warning from Firefox)):
// WITHOUT PROTOTYPING
var Person1 = function() {
this.name = 'myName';
this.changeName = function(name) {
this.name = name;
};
this.changeName2 = function(name) {
this.name = name;
};
this.changeName3 = function(name) {
this.name = name;
};
this.changeName4 = function(name) {
this.name = name;
};
}
// WITH PROTOTYPING, WITH MUTATION
var Person2 = function() {
this.name = 'myName';
}
Person2.prototype = {
changeName: function(name) {
this.name = name;
},
changeName2: function(name) {
this.name = name;
},
changeName3: function(name) {
this.name = name;
},
changeName4: function(name) {
this.name = name;
}
};
// WITH PROTOTYPING, WITHOUT MUTATION
var Person3 = function() {
this.name = 'myName';
}
Person3.prototype.changeName = function(name) {
this.name = name;
};
Person3.prototype.changeName2 = function(name) {
this.name = name;
};
Person3.prototype.changeName3 = function(name) {
this.name = name;
};
Person3.prototype.changeName4 = function(name) {
this.name = name;
};
// DO THE TEST
var i=0, len=1000000;
// TEST1
window.performance.mark('mark_test_start');
for(i=0;i<len;i++) {
p = new Person1();
p.changeName('myName2');
}
window.performance.mark('mark_test_end');
window.performance.measure('no-prototyping', 'mark_test_start', 'mark_test_end');
// TEST2
window.performance.mark('mark_test2_start');
for(i=0;i<len;i++) {
p = new Person2();
p.changeName('myName2');
}
window.performance.mark('mark_test2_end');
window.performance.measure('prototyping-with-mutation', 'mark_test2_start', 'mark_test2_end');
// TEST3
window.performance.mark('mark_test3_start');
for(i=0;i<len;i++) {
p = new Person2();
p.changeName('myName2');
}
window.performance.mark('mark_test3_end');
window.performance.measure('prototyping-without-mutation', 'mark_test3_start', 'mark_test3_end');
// OUTPUT tests
var items = window.performance.getEntriesByType('measure');
for (var i = 0; i < items.length; ++i) {
var req = items[i];
console.log(req.name + ': ' + req.duration.toFixed(2));
}
I need to use logic like visitor pattern and I've created new
sample which failed in visitor.visit(self); and I got error undefined is not a function,
any idea what am I missing?
var Entity = function (file,name) {
var self = this;
var name;
var type;
var log = {};
this.setName = function (name) {
this.name = name;
};
this.accept = function (visitor) {
visitor.visit(self);
};
this.getName = function () {
return name;
};
this.getType = function () {
return type;
};
this.getLog = function () {
return log;
};
};
//Start using visitor
var verifyFile = function () {
this.visit = function (file) {
alert("test");
};
};
function test(){
var file = new Entity();
file.accept(verifyFile);
};
You are injecting a function that defines a function, but your code is looking for an object that contains a function - see below
var Entity = function(file, name) {
var self = this;
var name;
var type;
var log = {};
this.setName = function(name) {
this.name = name;
};
this.accept = function(visitor) {
visitor.visit(self);
};
this.getName = function() {
return name;
};
this.getType = function() {
return type;
};
this.getLog = function() {
return log;
};
};
//Start using visitor
var verifyFile = {
visit : function(file) {
alert("test");
}
};
function test() {
var file = new Entity();
file.accept(verifyFile);
};
test()
i'm practicing with Javascript Inheritance, my first try is following code:
var base_class = function()
{
var _data = null;
function _get() {
return _data;
}
this.get = function() {
return _get();
}
this.init = function(data) {
_data = data;
}
}
var new_class = function() {
base_class.call(this);
var _data = 'test';
function _getData() {
return this.get();
}
this.getDataOther = function() {
return _getData();
}
this.getData = function() {
return this.get();
}
this.init(_data);
}
new_class.prototype = base_class.prototype;
var instance = new new_class();
alert(instance.getData());
alert(instance.getDataOther());
to that point i am really happy with my solution, but there is one problem
that i dont get resolved.
the "getDataOther" method don`t return the stored data from the base class,
because i cannot access the public "get" class from the protected "_getData" method in the new_class.
How can i get that running ?
Thanks in advance.
Ps.: Please excuse my poor English
If you comment out the this.init function (which overwrites the base_class _data field) and make the new_class's getData function just return _data, you should be able to get distinct variables.
var base_class = function()
{
var _data = null;
function _get() {
return _data;
}
this.get = function() {
return _get();
}
this.init = function(data) {
_data = data;
}
}
var new_class = function() {
var self = this; //Some browsers require a separate this reference for
//internal functions.
//http://book.mixu.net/ch4.html
base_class.call(this);
var _data = 'test';
function _getData() {
return self.get();
}
this.getDataOther = function() {
return _getData();
}
this.getData = function() {
return _data; //Changed this line to just return data
//Before, it did the same thing as _getData()
}
//this.init(_data); //Commented out this function (it was changing the base_class' data)
}
new_class.prototype = base_class.prototype;
var instance = new new_class();
alert(instance.getData());
alert(instance.getDataOther());
Your english is fine by the way :)