Have knockout observable check for null - asp.net

I was wondering if there was a way to have knockout check to see if data is null before it tries to put it into an observable?
Right now I do this:
if (!data.Filename) {
this.FileName = ko.observable("");
}
else {
this.FileName = ko.observable(data.Filename);
}
Otherwise a null value in the data will cause the entire property not to show up. Is there a way to use extenders or something that I can add a null check to without having to do this with every property? My data has nulls in random places that I can't control and I don't want the property not to show up because one row in the dataset has a null value for that property.
Seems like there should be a better way to do this.

heh
There are a number of ways to do this. What I would do is
var self = this;
self.fileName = ko.observable(data.Filename);
self.fileNameComputed = ko.computed(function(){
return self.fileName() || ""
});
Then, in your mark up reference the computed instead if the observable.

In Javascript there are other patterns available to do this.
The first, and simplest, is akin to the ?? operator in C#:
function ViewModel(data) {
data = data || {};
this.Filename .observable(data.Filename || "");
}
The || operator will return the left operand unless it is falsy, then it'll fall back to the second argument. My example above will:
Make sure data itself is "at least" an empty object (where .Filename would be undefined);
Make sure that the input to ko.observable(...) is "at least" the empty string.
A second option would be to use default options. An example that utilizes jQuery to merge input data and default options:
var defaultData = {
Filename: "enter-a-file" // could also be empty string of course!
};
function ViewModel(data) {
var dto = $.extend({}, defaultData, data);
this.Filename = ko.observable(dto.Filename);
}
This will "fold" data into defaultData, and fold that result into an empty, fresh object, making sure the dto variable holds the merged result. The rest of your function can then safely assume a fully populated input variable.
The third and final option I'll mention is a remix of QBM5's answer, but I agree with the commenter's there that if you can use a pureComputed (which, in your example, is perfectly fine), you probably should:
function ViewModel(data) {
var self = this;
data = data || {};
this.Filename = ko.observable(data.Filename);
this.FilenameText = ko.pureComputed(function() {
return self.Filename() || "";
});
}
PS. You didn't have the underlying issue you mention because you spell FileName and Filename with different capitalization on this and data respectively, didn't you? ;-)

Related

How to get data from firebase query based on value from another firebase query in FutureBuilder in Flutter?

I am new to flutter and I am sure there is a simple way of doing this. Let me first give you a background. I have 2 tables(collections). The first one store a mapping. Therefore it returns a key based on an id which will be used to query the second table and retrieve the data from firebase.
I have written 2 data models and 2 functions which return Future<> data. They are as follows-
Future<SpecificDevice> getSpecificDevice(String deviceId) {
Future<SpecificDevice> obj =_database.reference().child("deviceMapping").orderByChild("deviceId").equalTo(deviceId).once().then((snapshot) {
SpecificDevice specificDevice = new SpecificDevice(deviceId, "XXXX", new List<String> ());
if(snapshot.value.isNotEmpty){
print(snapshot.value);
snapshot.value.forEach((key,values) {
if(values["deviceId"] == deviceId) {
specificDevice.deviceKey = values["deviceDesc"];
specificDevice.vendorList = List.from(values["vendorList"]);
}
});
}
return specificDevice;
});
return obj;
}
This function gets the mapping deviceId -> deviceKey.
This is the key of record stored in another table. Following is the function for it.
Future<Device> getDeviceDescription(String deviceKey) {
Future<Device> device = _database.reference().child("deviceDescription").once().then((snapshot) {
Device deviceObj = new Device("YYYY", "YYYY", "YYY", "YYYY", "YYYY");
if(snapshot.value.isNotEmpty){
print(snapshot.value);
//Future<SpecificDevice> obj = getSpecificDevice(deviceId);
//obj.then((value) {
snapshot.value.forEach((key,values) {
if(key == deviceKey) { // compare with value.deviceKey instead
print(values["deviceDescription"]); // I get the correct data here.
deviceObj.manual = values["deviceManual"];
deviceObj.deviceType = values["deviceType"];
deviceObj.description = values["deviceDescription"];
deviceObj.brand = values["deviceBrand"];
deviceObj.picture = values["devicePicture"];
}
// });
});
}
return deviceObj;
});
return device;
}
Now both of these functions work. I want to make it work one after the other. In the above function, if I uncomment the lines of code, the data is retrieved properly in the inner function but it returns initial default values set because the values get returned before setting the obj of SpecificDevice.
Here is where I am getting the error. I am calling the second function in FutureBuilder<> code with the above lines uncommented and taking input param as deviceId.
return FutureBuilder<Device>(
future: getDeviceDescription(deviceId),
builder:(BuildContext context,AsyncSnapshot snapshot){... // using snapshot.data in its child.
Here in snapshot.data. would give me YYYY. But it should get me the value from the database.
I am stuck with this for a while. Any help in fixing this? or if what I am trying to do is clear then please suggest me a better way to approach this. Thanks in advance!
The answer is rather simple:
first and foremost - you forgot to use async / await keywords, which will guarantee synchronous data retrieval from the database. Always use them, if you are connecting to any network service
to make one command work after another - use .then((value) {}). It will get data from the first function (which you pass using return) and use it in the second function.
Solved the problem by changing the calling function to -
return FutureBuilder<Device>(
future: getSpecificDevice(deviceId).then((value){
return getDeviceDescription(value.deviceKey);
}),
builder:(BuildContext context,AsyncSnapshot snapshot){

Update collection with an array in firebase

I need to update a collection in values like this :
{
"email" : "x#gmail.com",
"fullName" : "Mehr",
"locations" : ["sss","dsds","adsdsd"]
}
Locations needs to be an array. in firebase how can I do that ... and also it should check duplicated.
I did like this :
const locations=[]
locations.push(id)
firebase.database().ref(`/users/ + ${userId}`).push({ locations })
Since you need to check for duplicates, you'll need to first read the value of the array, and then update it. In the Firebase Realtime Database that combination can is done through a transaction. You can run the transaction on the locations node itself here:
var locationsRef = firebase.database().ref(`/users/${userId}/locations`);
var newLocation = "xyz";
locationsRef.transaction(function(locations) {
if (locations) {
if (locations.indexOf(newLocation) === -1) {
locations.push(newLocation);
}
}
return locations;
});
As you can see, this loads the locations, ensures the new location is present once, and then writes it back to the database.
Note that Firebase recommends using arrays for set-like data structures such as this. Consider using the more direct mapping of a mathematical set to JavaScript:
"locations" : {
"sss": true,
"dsds": true,
"adsdsd": true
}
One advantage of this structure is that adding a new value is an idempotent operation. Say that we have a location "sss". We add that to the location with:
locations["sss"] = true;
Now there are two options:
"sss" was not yet in the node, in which case this operation adds it.
"sss" was already in the node, in which case this operation does nothing.
For more on this, see best practices for arrays in Firebase.
you can simply push the items in a loop:
if(locations.length > 0) {
var ref = firebase.database().ref(`/users/ + ${userId}`).child('locations');
for(i=0; i < locations.length; i++) {
ref.push(locations[i]);
}
}
this also creates unique keys for the items, instead of a numerical index (which tends to change).
You can use update rather than push method. It would much easier for you. Try it like below
var locationsObj={};
if(locations.length > 0) {
for(i=0; i < locations.length; i++) {
var key= firebase.database().ref(`/users/ + ${userId}`).child('locations').push().key;
locationsObj[`/users/ + ${userId}` +'/locations/' + key] =locations[i];
}
firebase.database().ref().update(locationsObj).then(function(){// which return the promise.
console.log("successfully updated");
})
}
Note : update method is used to update multiple paths at a same time. which will be helpful in this case, but if you use push in the loop then you have to wait for the all the push to return the promises. In the update method it will take care of the all promises and returns at once. Either you get success or error.

Checking for existence of $firebaseObject

For a normal Javascript object on $scope, you might use ngShow with a div to make the div's presence depend on the existence of the object.
$scope.myObj = null;
// And then later
$scope.myObj = {arbitrary:{number:{of:"objects"}}};
...
<div ng-show="myObj">{{myObj}}</div>
But if you tie an object to a $firebaseObject
var fbObjRef = new Firebase(FirebaseURL).child("fbObj")
$scope.myObj = $firebaseObject(fbObjRef);
Then your ngShow won't work because a reference that is empty in Firebase will still be represented client side by an object that looks like:
{
"$id":"fbObj",
"$priority":null,
"$value":null
}
And then later if non-primitive content is set at that reference, the $value key disappears and is replaced by the content:
{
"$id":"fbObj",
"$priority":null,
"someKey":{
"anotherKey":"someValue"
}
}
What's the best way to check against the existence of the $firebaseObject? Here's what I'm doing but it feels clunky. Maybe this is an opportunity to add an $exists key to the AngularFire API.
<div ng-show="myObjExists()">{{myObj}}</div>
...
$scope.myObjExists = function(){
return !(
$scope.myObj.hasOwnProperty("$value")
&& $scope.myObj.$value === null
);
};

How to define a persistent property in JXA

In AppleScript I would write
property foo: "value"
and the value would be saved between runs. How can I do this in Javascript for Automation?
JavaScript for Automation doesn't have a direct parallel for the persistent property (and global value) mechanism of AS, but it does have JSON.stringify() and JSON.parse(), which work well for simple serialisation and retrieval of state.
Perhaps something broadly like:
(function () {
'use strict';
var a = Application.currentApplication(),
sa = (a.includeStandardAdditions = true, a),
strPath = sa.pathTo('desktop').toString() + '/persist.json';
// INITIALISE WITH RECOVERED VALUE || DEFAULT
var jsonPersist = $.NSString.stringWithContentsOfFile(strPath).js || null,
persistent = jsonPersist && JSON.parse(jsonPersist) || {
name: 'perfume',
value: 'vanilla'
};
/*********************************************************/
// ... MAIN CODE ...
// recovered or default value
sa.displayNotification(persistent.value);
// mutated value
persistent.value = "Five Spice"
/*********************************************************/
// WRAP UP - SERIALISE TO JSON FOR NEXT SESSION
return $.NSString.alloc.initWithUTF8String(
JSON.stringify(persistent)
).writeToFileAtomically(strPath, true);
})();
(A fuller example here: https://github.com/dtinth/JXA-Cookbook/wiki/Examples#properties-which-persist-between-script-runs )
Or, for simple key-value pairs rather than arbitrary data structures, see:
https://stackoverflow.com/a/31902220/1800086 on JXA support for writing and reading .plist

In MVC app using JQGrid - how to set user data in the controller action

How do you set the userdata in the controller action. The way I'm doing it is breaking my grid. I'm trying a simple test with no luck. Here's my code which does not work. Thanks.
var dataJson = new
{
total =
page = 1,
records = 10000,
userdata = "{test1:thefield}",
rows = (from e in equipment
select new
{
id = e.equip_id,
cell = new string[] {
e.type_desc,
e.make_descr,
e.model_descr,
e.equip_year,
e.work_loc,
e.insp_due_dt,
e.registered_by,
e.managed_by
}
}).ToArray()
};
return Json(dataJson);
I don't think you have to convert it to an Array. I've used jqGrid and i just let the Json function serialize the object. I'm not certain that would cause a problem, but it's unnecessary at the very least.
Also, your user data would evaluate to a string (because you are sending it as a string). Try sending it as an anonymous object. ie:
userdata = new { test1 = "thefield" },
You need a value for total and a comma between that and page. (I'm guessing that's a typo. I don't think that would compile as is.)
EDIT:
Also, i would recommend adding the option "jsonReader: { repeatitems: false }" to your javascript. This will allow you to send your collection in the "rows" field without converting it to the "{id: ID, cell: [ data_row_as_array ] }" syntax. You can set the property "key = true" in your colModel to indicate which field is the ID. It makes it a lot simpler to pass data to the grid.

Resources