**
I don't want to print anything instead of "undefined" if I have not entered value next to "user1" (course count) in new user like : ("user1",2)
var User = function(firstName,courseCount){
this.firstName = firstName;
this.courseCount = courseCount;
this.getCourseCount = function(){
console.log(`Course count is: ${this.courseCount}`);
};
};
User.prototype.getFirstName = function () {
console.log(`User Name is : ${this.firstName}`);
};
var user1 = new User("user1",);
if (user1.hasOwnProperty("firstName")) {
user1.getFirstName();
}
if (user1.hasOwnProperty("getCourseCount")) {
user1.getCourseCount();
};
if (user1.hasOwnProperty("getCourseCount")) {
user1.getCourseCount();
};**
var User = function(firstName,courseCount){
this.firstName = firstName;
this.courseCount = courseCount?courseCount:'';
this.getCourseCount = function(){
console.log(`Course count is: ${this.courseCount}`);
};
};
User.prototype.getFirstName = function () {
console.log(`User Name is : ${this.firstName}`);
};
var user1 = new User("user1",);
if (user1.hasOwnProperty("firstName")) {
user1.getFirstName();
}
if (user1.hasOwnProperty("getCourseCount")) {
user1.getCourseCount();
};
var User = function(firstName,courseCount){
this.firstName = firstName;
this.courseCount = courseCount;
this.getCourseCount = function(){
if(this.courseCount===undefined){this.courseCount=""}
console.log(`Course count is: ${this.courseCount}`);
};
};
this will prevent to print undefined
Related
i reuse the same template in other route with different data argument but using the same publication...
if i do normal pub/sub, the data being published as expected. but when i do conditional pub/sub like below, i fail to subscribe the data. console log return empty array,,,
server/publication.js
Meteor.publish('ACStats', function(cId, uId) {
var selectors = {cId:cId, uId:uId};
var options = {
fields: {qId:0}
};
return ACStats.find(selectors,options);
});
client/onCreated
Template.channelList.onCreated(function() {
this.disable = new ReactiveVar('');
if (FlowRouter.getRouteName() === 'profile') {
var self = this;
self.autorun(function() {
var penName = FlowRouter.getParam('penName');
var u = Meteor.users.findOne({slugName:penName});
if (u) {var uId = u._id;}
Meteor.subscribe('ACStats', null, uId);
});
} else{
var self = this;
self.autorun(function() {
var channelName = FlowRouter.getParam('channel');
var c = Channels.findOne({title:channelName});
if (c) {var cId = c._id;}
Meteor.subscribe('ACStats', cId, null);
});
}
});
console
ACStats.find().fetch() //return empty array
anyone have figured out my mistake ..??
thank You so much....
You can make two publications:
Meteor.publish ('ACStatsChannels', cId, function() {
});
Meteor.publish ('ACStatsUsers', uId, function() {
})
And then subscribe like this:
Template.channelList.onCreated(function() {
this.disable = new ReactiveVar('');
var self = this;
self.autorun(function() {
if (FlowRouter.getRouteName() === 'profile') {
var penName = FlowRouter.getParam('penName');
self.subscribe('ACStatsUsers', penName);
} else {
var channelName = FlowRouter.getParam('channel');
self.subscribe('ACStatsChannels', channelName);
}
});
});
I am trying to build a function that creates a person by receiving at first a full name and using methods to set the first, last and full name. Afterwards it would have methods that should be able to change each part of the name.
My current code looks like this:
var Person = function(firstAndLast) {
var name = firstAndLast;
this.getFirstName = function() {
return name.substr(0,name.indexOf(' '));
};
this.getLastName = function() {
return name.substr(name.indexOf(' ')+1);
};
this.getFullName = function() {
return name;
};
this.setFirstName = function() {
return name;
};
this.setLastName = function() {
return name;
};
this.setFullName = function() {
return name;
};
};
var bob = new Person('Bob Ross');
bob.setFullName();
Now I am completely stuck when it gets time to pass a new name, so that if I do something like:
bob.setFullName('George Carlin');
and then pass:
bob.getFullName();
I should get the answer 'George Carlin'.
yet this isn't happening.
Thanks as always.
So the problem was that I wasn't really understanding how the values where being passed, and that instead of working on a full name I should be working on the parts.
var Person = function(firstAndLast) {
var firstName = firstAndLast.split(' ')[0];
var lastName = firstAndLast.split(' ')[1];
this.setFirstName = function(firstNameNew) {
firstName = firstNameNew;
};
this.setLastName = function(lastNameNew) {
lastName = lastNameNew;
};
this.setFullName = function (fullNameNew) {
firstName = fullNameNew.split(' ')[0];
lastName = fullNameNew.split(' ')[1];
};
this.getFullName = function() {
return firstName + ' ' + lastName;
};
this.getFirstName = function() {
return firstName;
};
this.getLastName = function() {
return lastName;
};
};
var bob = new Person('Bob Ross');
I'm having trouble converting JSON to Javascript objects when the JSON data has nested objects. The top level 'Person' object gets recreated fine, but the 'Residence' object property does not
function Person(first, last) {
this.FirstName = first;
this.LastName = last;
this.Residence = {};
}
Person.Revive = function (data) {
return new Person(data.FirstName, data.LastName);
}
Object.defineProperty(Person.prototype, "FullName", {
get: function() { return this.FirstName + " " + this.LastName; }
});
Person.prototype.toJSON = function () {
this.__class__ = "Person";
return this;
});
function Residence(lat, long) {
this.Latitude = lat;
this.Longitude = long;
}
Residence.prototype.toJSON = function () {
this.__class__ = "Residence";
return this;
}
Residence.Revive = function (data) {
return new Residence(data.Latitude, data.Longitude);
}
Object.defineProperty(Residence.prototype, "Location", {
get: function () { return this.Latitude + ", " + this.Longitude; }
});
var p = new Person("Foo", "Bar");
p.Residence = new Residence(44, 33);
console.log("Full name = " + p.FullName);
console.log("Location = " + p.Residence.Location);
var serialization = JSON.stringify(p);
console.log(serialization);
var rawObj = JSON.parse(serialization, function (key, value) {
if (value instanceof Object && value.__class__ == 'Person') {
return Person.Revive(value);
}
if (value instanceof Object && value.__class__ == 'Residence') {
return Residence.Revive(value);
}
return value;
});
console.log("Full name = " + rawObj.FullName);
console.log("Location = " + rawObj.Residence.Location);
The JSON.parse function does get a key/value pair for the 'Residence' object, and a new Residence object is created and returned. However, the resulting 'rawObj.Residence' is just an empty object. Can anyone point out what I'm doing wrong?
The console output is as follows:
Full name = Foo Bar
Location = 44, 33
{"FirstName":"Foo","LastName":"Bar","Age":22,"Residence":{"Latitude":44,"Longitude":33,"__class__":"Residence"},"__class__":"Person"}
Full name = Foo Bar
Location = undefined
Fiddle: http://jsfiddle.net/CadGuy/yyq4dqtx/
var p = new Person("Foo", "Bar");
p.Residence = new Residence(44, 33);
Well, if you are constructing your Person objects like that, you'll have to revive them like this as well:
Person.Revive = function (data) {
var p = new Person(data.FirstName, data.LastName);
p.Residence = data.Residence;
return p;
};
Of course, it might be a good idea to make the residence an (optional?) parameter to Person in the first place.
I want to be able to assign default values to variables when I'm using prototyping for object creation.
When I try to assign default values to the variables they are always 'undefined'.
I have tried to find the answer but all the possible solutions I have tried dont work.
My questions are:
why do a variable that have I have initiated with a value has the value 'undefined'
how do I solve my problem?
(function() {
EmployeeNS = {};
EmployeeNS.Employee = function() {
var _firstName;
var _lastName;
var _employeeID = 'Unassigned';
}
EmployeeNS.Employee.prototype.setFirstName = function(fName) { this._firstName = fName; };
EmployeeNS.Employee.prototype.getFirstName = function() { return this._firstName; };
EmployeeNS.Employee.prototype.setLastName = function(lName) { this._lastName = lName; };
EmployeeNS.Employee.prototype.getLastName = function() { return this._lastName; };
EmployeeNS.Employee.prototype.setEmployeeID = function(employeeID) { this._employeeID = employeeID; };
EmployeeNS.Employee.prototype.getEmployeeID = function() { return this._employeeID; };
EmployeeNS.Worker = function() {
var _department;
}
EmployeeNS.Worker.prototype = new EmployeeNS.Employee();
EmployeeNS.Worker.prototype.constructor = Worker;
EmployeeNS.Worker.prototype.setDepartment = function(department) { this._department = department; };
EmployeeNS.Worker.prototype.getDepartment = function() { return this._department; };
})();
function createWorker() {
var x = new EmployeeNS.Worker();
x.setFirstName("John");
x.setLastName("Doe");
x.setDepartment("Transport");
var message = x.getFirstName()
+ " "
+ x.getLastName()
+ " (Department: "
+ x.getDepartment()
+ " / EmployeeID: "
+ x.getEmployeeID()
+ ")";
alert(message);
}
Thanks
you can simply make it to work by changing like this,
EmployeeNS.Employee = function() {
this._firstName;
this._lastName;
this._employeeID = 'Unassigned';
}
Try out this way , you can make those variables truly private by wrapping Employee ,
(function() {
EmployeeNS = {};
(function() {
var _firstName;
var _lastName;
var _employeeID = 'Unassigned';
EmployeeNS.Employee = function() {
}
EmployeeNS.Employee.prototype.setFirstName = function(fName) { _firstName = fName; };
EmployeeNS.Employee.prototype.getFirstName = function() { return _firstName; };
EmployeeNS.Employee.prototype.setLastName = function(lName) { _lastName = lName; };
EmployeeNS.Employee.prototype.getLastName = function() { return _lastName; };
EmployeeNS.Employee.prototype.setEmployeeID = function(employeeID) { _employeeID = employeeID; };
EmployeeNS.Employee.prototype.getEmployeeID = function() { return _employeeID; };
})();
(function() {
var _department;
EmployeeNS.Worker = function() {
}
EmployeeNS.Worker.prototype = new EmployeeNS.Employee();
EmployeeNS.Worker.prototype.constructor = Worker;
EmployeeNS.Worker.prototype.setDepartment = function(department) { _department = department; };
EmployeeNS.Worker.prototype.getDepartment = function() { return _department; };
})();
})();
Here is the jsfiddle
If you want instance properties, do it like this:
(function() {
EmployeeNS = {};
EmployeeNS.Employee = function () {
this._firstName = null;
this._lastName = null;
this._employeeID = 'Unassigned';
};
EmployeeNS.Employee.prototype.setFirstName = function(fName) {
this._firstName = fName;
};
})();
Hi I am using phonegap to develop a shopping app. I want to give the user an option to save their order and complete wheneven he/she finds convenient. My question where do I save the order data. Local file system or local db of the mobile device? I will like to save the order
in json format in a local file. Please suggest the best option for me. Also a snippet will be highly appreciated. Thanks
You could also use HTML5 localStorage as an easier alternative to file storage. I have been using an encapsulated version of localStorage to facilitate get/set operations and decrease namespace pollution. Please see code base below:
/**
* The class is designed to facilitate flexible permanent storage of key value
* pairs utilzing HTML5 localStorage.
*
* #class LocalMap
* #author Zorayr Khalapyan
* #version 10/25/2012
*/
var LocalMap = function ( name ) {
var that = {};
//Prevent compatability issues in different execution environments.
if ( !localStorage ) {
localStorage = {};
}
if ( !localStorage[name] ) {
localStorage[name] = "{}";
}
var setMap = function ( map ) {
localStorage[name] = JSON.stringify( map );
};
that.getMap = function () {
return JSON.parse( localStorage[name] );
};
/**
* Stores the specified (key, value) pair in the localStorage
* under the map's namespace.
*/
that.set = function ( name, object ) {
var map = that.getMap();
map[ name ] = object;
setMap( map );
};
that.get = function ( name ) {
var map = that.getMap();
return typeof( map[ name ] ) !== "undefined" ? map[name] : null;
};
that.importMap = function ( object ) {
var map = that.getMap();
var key;
for ( key in object ) {
if (object.hasOwnProperty(key)) {
map[key] = object[key];
}
}
setMap(map);
};
that.length = function () {
var map = that.getMap();
var size = 0, key;
for (key in map) {
if (map.hasOwnProperty(key)) size++;
}
return size;
};
that.erase = function () {
localStorage[name] = JSON.stringify({});
};
that.isSet = function (name) {
return that.get(name) != null;
};
that.release = function (name) {
var map = that.getMap();
if (map[name]) {
delete map[name];
}
setMap(map);
};
that.deleteNamespace = function(){
if (localStorage.hasOwnProperty(name)) {
delete localStorage[name];
}
};
return that;
};
LocalMap.destroy = function () {
for ( var item in localStorage ) {
if ( localStorage.hasOwnProperty( item ) ) {
delete localStorage[ item ];
}
}
};
LocalMap.exists = function (name) {
return (localStorage[name]) ? true : false;
};
Below are the unit tests for get and set functions:
test( "Test set()", function() {
var map = LocalMap('test-namespace');
///
map.set("var-1", "val-1");
map.set("var-2", "val-2");
map.set("var-3", "val-3");
//
ok(map.isSet("var-1"), "A variable should be successful set.");
ok(map.isSet("var-2"), "A variable should be successful set.");
ok(map.isSet("var-3"), "A variable should be successful set.");
});
test( "Test get()", function() {
var map = LocalMap('test-namespace');
map.set("var-1", "val-1");
map.set("var-2", "val-2");
map.set("var-3", "val-3");
///
var var1 = map.get("var-1");
var var2 = map.get("var-2");
var var3 = map.get("var-3");
var var4 = map.get("var-4");
//
equal(var1, "val-1", "A set variable should be succesfully retreived.");
equal(var2, "val-2", "A set variable should be succesfully retreived.");
equal(var3, "val-3", "A set variable should be succesfully retreived.");
equal(var4, null, "A variable that was not set should not be retreived.");
});
Hope this helps, and let me know if you have any questions.
How about the below code? I copied it from here. Actually I like its code.
// define dbContext & entities------------------------------------
var DemoDataContext = function () {
nova.data.DbContext.call(this, "Demo", "1.0", "Demo DB", 1000000);
this.users = new nova.data.Repository(this, User, "users");
this.roles = new nova.data.Repository(this, Role, "roles");
};
DemoDataContext.prototype = new nova.data.DbContext();
DemoDataContext.constructor = DemoDataContext;
var User = function () {
nova.data.Entity.call(this);
this.name = "";
this.password = "";
this.birthYear = 1980;
this.createdDate = new Date();
this.deleted = false;
};
User.prototype = new nova.data.Entity();
User.constructor = User;
var Role = function () {
nova.data.Entity.call(this);
this.name = "";
this.createdDate = new Date();
};
Role.prototype = new nova.data.Entity();
Role.constructor = Role;
// end define dbContext & entities------------------------------------
// service methods----------------------------------------------------
function getAllUsers(callback) {
new DemoDataContext().users.toArray(function (users) {
alert(users.length);
callback(users);
});
}
function getUserByName(name, callback) {
new DemoDataContext().users.where("name='" + name + "'").toArray(function (users) {
callback(users.firstOrDefault());
});
}
function addRole(roleName, callback) {
var role = new Role();
role.name = roleName;
var db = new DemoDataContext();
db.roles.add(role);
db.saveChanges(callback);
}
function updateUserPassword(username, password, callback) {
getUserByName(username, function (user) {
if (user == null) {
throw "no user found.";
}
user.password = password;
var db = new DemoDataContext();
db.users.update(user);
db.saveChanges(callback);
});
}
function deleteUserByName(name, callback) {
getUserByName(name, function (user) {
if (user == null) {
throw "no user found.";
}
var db = new DemoDataContext();
db.users.remove(user);
db.saveChanges(callback);
});
}
// end service methods----------------------------------------------------