How to access observable values? - javascript

This is a model and I am trying to access its values. But value is in Symbol(_latestValue) and I am not sure how I can access that value.
define(['services/SessionService'],
function(SessionService) {
var uiModel = function(index, data) {
this.origData = data;
this.sessionID = data.sessionID;
this.rowNumber = index + 1;
this.FullName = ko.observable('');
this.accountId = ko.observable('');
this.organizationId = ko.observable('');
this.userId = ko.observable('');
this.BuyerEmail = ko.observable('');
this.Address = ko.observable('');
this.loadSessionInfo();
};
uiModel.prototype.loadSessionInfo = function() {
var self = this;
var service = new SessionService();
service.getSessionInfo(this.sessionID).then(function(result) {
self.FullName(result.Buyer1Name);
self.BuyerEmail(result.BuyerEmail);
self.Address(result.Address);
self.accountId(result.AccountID);
self.organizationId(result.OrganizationID);
self.userId(result.UserID);
});
};
return uiModel;
});
Attached is the image that shows values that I am receiving are in Symbol(_latestValue).

Related

Can i use $angular timeout in a return statement?

I am using Parse data, but the deal is, i want to return the variable ParseUserArray, but just after it passing by the success promisse. I was wondering how can i do that.
var UserWs = angular.module('UserWs', []);
UserWs.service('UserWsService', ['parseInit', function(parseInit){
var service = this;
this.getUserAtParse = function(id){
var user = Parse.Object.extend("User");
var query = new Parse.Query(user);
var parseUserArray = [];
query.find({
success: function(anUser) {
for (var i = 0; i < anUser.length; i++) {
var newUser = new User(anUser[i]);
parseUserArray.push(newUser);
}
console.log(parseUserArray);
}
});
var User =function(anUser){
this.id = anUser.id;
this.name = anUser.get("name");
this.email = anUser.get("username");
this.company = anUser.get("company");
}
return parseUserArray;
};
thanks in advance :)
You can use promise for this - $q service
var UserWs = angular.module('UserWs', []);
UserWs.service('UserWsService', ['$q', 'parseInit', function($q, parseInit) {
var service = this;
this.getUserAtParse = function(id) {
var defer = $q.defer();
var user = Parse.Object.extend("User");
var query = new Parse.Query(user);
var parseUserArray = [];
query.find({
success: function(anUser) {
for (var i = 0; i < anUser.length; i++) {
var newUser = new User(anUser[i]);
parseUserArray.push(newUser);
}
console.log(parseUserArray);
defer.resolve(parseUserArray);
}
});
var User = function(anUser) {
this.id = anUser.id;
this.name = anUser.get("name");
this.email = anUser.get("username");
this.company = anUser.get("company");
}
return defer.promise;
}
}]);
UserWs.controller('sampleCtrl', ['$scope', 'UserWsService', function($scope, UserWsService) {
UserWsService.getUserAtParse(SOME_ID).then(function(resultArray) {
//logic here
});
}]);

KNockout JS - Automatic reload of ajax call

Hi folks trying to get a simple setintervel working to automatically refresh my data every minute. The line im having issues with is this:
setInterval(incidentViewModel.fetchdata,60000);
I had also tried this:
window.setInterval(incidentViewModel.fetchdata,60000);
Both of these give me the same error:
Uncaught TypeError: self.incidents is not a function
Im not seeing anything obvious that's causing the problem, would anyone have any idea?
Here is my full code:
function IncidentViewModel() {
var self = this;
self.incidents = ko.observableArray();
self.currentIncident = ko.observable();
self.showModal = ko.observable(false);
self.fetchdata = function() {
Incident.BASE_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents';
Incident.CREATE_HEADERS = {"accept": "application/json;odata=verbose"};
Incident.UPDATE_HEADERS = {"accept": "application/json;odata=verbose","If-Match": "*"};
var self = this;
$.getJSON(Incident.BASE_URL+filterlist+orderlist,
function(data) {
if (data.d.results) {
self.incidents(data.d.results.map(function(item) {
return new Incident(item);
}));
$('#loading').hide("slow");
$('#IncidentTable').show("slow");
} else {
console.log("no results received from server");
}
}).fail(function() {
console.log("error", params, arguments);
});
console.log("Im done fetching data, pheww!");
}
}
function DataItem(data) {
//console.log(data);
this.Name = ko.observable(data.Name);
this.Price = ko.observable(data.Price);
}
function Incident(data) {
var self = this;
self.ID = data.ID;
self.Description = ko.observable(data.Description);
self.Composante = ko.observable(data.Composante);
self.Incident = ko.observable(data.Incident);
self.ÉtatValue = ko.observable(data.ÉtatValue);
self.PrioritéValue = ko.observable(data.PrioritéValue);
self.Duré = ko.observable(data.Duré);
self.Date_de_début = ko.observable(data.Date_de_début);
self.Date_de_fin = ko.observable(data.Date_de_fin);
self.Groupe_Support_Prime = ko.observable(data.Groupe_Support_Prime);
self.Autres_Groupe_Support_Prime = ko.observable(data.Autres_Groupe_Support_Prime);
self.ResponsableValue = ko.observable(data.ResponsableValue);
self.Impact = ko.observable(data.Impact);
self.Temps_Consacré = ko.observable(data.Temps_Consacré);
self.Type_de_tempsValue = ko.observable(data.Type_de_tempsValue);
self.Journal_des_actions = ko.observable(data.Journal_des_actions);
self.Dépanage = ko.observable(data.Dépanage);
self.Journal_des_actions = ko.observable(data.Journal_des_actions);
self.Suivi = ko.observable(data.Suivi);
self.Ressources = ko.observable(data.Ressources);
}
var incidentViewModel = new IncidentViewModel();
ko.applyBindings(incidentViewModel);
setInterval(incidentViewModel.fetchdata,60000);
Remove var self = this; inside the self.fetchdata function because you should be referring to the self inside the IncidentViewModel function when referring to self.incidents().

javascript constructors involving unknown amounts of arguments...

I was messing with some js on codecadamy and got a bit sidetracked trying to make something work.
In essence I was creating a few objects that are loaded into a controller object and set as properties of it with two functions that print the properties and compare a string to the name property of each object in the controller.
I noticed I can do it if I make the objects in the prototype style and specify a normal function to handle setting the properties like so:
var friends = {};
friends.setUp = function() {
this.friends = [];
for(var i in arguments) {
arguments[i].setUp();
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = {};
bill.setUp = function() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
var steve = {};
steve.setUp = function() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
var mike = {};
mike.setUp = function() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
friends.setUp(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
However if I do it with constructors It does not work, example:
function bill() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
function steve() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
function mike() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
function friends() {
this.friends = [];
for(var i in arguments) {
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
I was wondering if this is a limitation of using constructors or am I messing up the syntax somewhere? Thank you!
This doesn't appear to have anything to do with constructors with an unknown number of arguments, but rather you are not assigning methods on your objects appropriately. They need to be put on the prototype so that they will be inherited by all objects that are created by this particular constructor. So in your code, these:
friends.list = function() {...}
friends.search = function() {...}
needs to be changed to:
friends.prototype.list = function() {...}
friends.prototype.search = function() {...}
Like this:
friends.prototype.list = function() {
for(var i = 0; i < this.friends.length; i++) {
console.log(this.friends[i]);
}
};
friends.prototype.search = function(name) {
for(var i = 0; i < this.friends.length; i++) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
Then, this code should work fine:
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
And, then the code works as you would expect here: http://jsfiddle.net/jfriend00/ba4me8ua/
FYI, you'll noticed that I changed the way you iterate through the arguments object items to be more array-like and avoid any chance of getting any non-numeric properties in the iteration.

Define a promise creating a new Service Object

I have a question about the promise system in AngularJS and the creation of services. I have a service called Customer:
angular.module("app").factory("Customer", ["CustomerDBServices", "OfficesList", "$q",
function(CustomerDBServices, OfficesList, $q){
return function(customerID){
var self = this;
//attributes
this.name = null;
this.ID = null;
this.code = null;
this.isVisible = 1;
this.showOffices = true;
this.offices = new OfficesList();
//constructor
if(typeof customerID !== "undefined"){
var metacustomer = CustomerDBServices.find({ID:customerID}, function(){
self.name = metacustomer.results.customer_name;
self.ID = metacustomer.results.customer_ID;
self.code = metacustomer.results.customer_internal_code;
self.isVisible = metacustomer.results.customer_is_visible;
self.getOffices();
});
}
//add office to customer
this.addNewOffice = function(){
self.offices.addNewOffice();
};
//remove office from customer
this.removeOffice = function(officeIndex){
self.offices.removeOffice(officeIndex);
};
//show offices
this.toggleOfficeVisibility = function(officeIndex){
self.offices.toggleOfficeVisibility(officeIndex);
};
}]);
In the "constructor" part of this service there is an AJAX call to a service that loads the attributes of the customer from the database. This is an async task. How can I create a promise in this situation? I use the customer service like this:
var customer = new Customer(ID);
and I would like to do something like
var customer = new Customer(ID).then(
function(){...}, //success
function(){...} //error
);
To do this I need a promise. Do I have to program a method create() within the customer service?
angular.module("app").factory("Customer", ["CustomerDBServices", "OfficesList", "$q",
function(CustomerDBServices, OfficesList, $q){
return function(customerID){
var self = this;
//attributes
this.name = null;
this.ID = null;
this.code = null;
this.isVisible = 1;
this.showOffices = true;
this.offices = new OfficesList();
//costructor
this.create = function(){
if(typeof customerID !== "undefined"){
var rest = $q.defer();
var metacustomer = CustomerDBServices.find({ID:customerID}, function(){
self.name = metacustomer.results.customer_name;
self.ID = metacustomer.results.customer_ID;
self.code = metacustomer.results.customer_internal_code;
self.isVisible = metacustomer.results.customer_is_visible;
self.getOffices();
rest.resolve("ok!");
});
return rest.promise;
}
}
...
...
...
}]);
and then use that stuff like this?
var customer = new Customer();
customer.create(ID).then(
function(){...},
function(){...},
)
Isn't there a way to call the "new Customer" and receive a promise? Thank you in advance!
Like I said in my comment I recommend against this approach. Putting complex asynchronous logic in a constructor is usually confusing and does not make for a very good or clear API.
That said, You don't need a .create method.
The trick is: If a function called as a constructor returns an object in JavaScript - it is returned instead of the this value.
Sparing you the whole Angular around it:
function(CustomerDBServices, OfficesList, $q){
return function(customerID){
var p = $q.defer();
var that = p.promise; // our 'that' is now a promise
//attributes
that.name = null;
that.ID = null;
that.code = null;
that.isVisible = 1;
that.showOffices = true;
that.offices = new OfficesList();
// use `that` instead of this in additional code
if(typeof customerID !== "undefined"){
var metacustomer = CustomerDBServices.find({ID:customerID}, function(){
self.name = metacustomer.results.customer_name;
self.ID = metacustomer.results.customer_ID;
self.code = metacustomer.results.customer_internal_code;
self.isVisible = metacustomer.results.customer_is_visible;
self.getOffices();
that.resolve("ok!");
});
}
return that; // we return the promise here.
}

How to make variables computed after its initializing

I am trying to set a variable that will depend on two others, but I don't want that computed
variable reacts on the initializing of one of these vars.
var viewModel = function() {
var self = this;
self.first = ko.observable("");
self.second = ko.observable();
self.doSmth = function() {
self.second(self.second() + 1);
};
self.init = function(o){
self.second(o);
};
self.comp = ko.computed(function(){
self.first();
self.second();
alert(self.second());
});
};
var vm = new viewModel();
ko.applyBindings(vm);
vm.init(111);
http://jsfiddle.net/TCAHS/1/
Alert message should appear only when I click on the button and dependent variable value was changed. And no messages with 'undefined' and init value '111'. Is there any built-in solution? Thanks.
I'll go with the easy solution... what about setting a flag to check whether the observable has been initialized, something like:
var viewModel = function() {
var self = this;
self.first = ko.observable("");
self.second = ko.observable();
self.doSmth = function() {
self.second(self.second() + 1);
};
self.init = function(o){
self.second(o);
};
var initialized = false;
self.comp = ko.computed(function(){
self.first();
self.second();
if (initialized) {
alert(self.second());
}
initialized = true;
});
};
var vm = new viewModel();
ko.applyBindings(vm);
vm.init(111);
And here's the fiddle.

Categories