Dwill Dwill - 1 year ago 46
C# Question

Get Object from KO.Observable

Sorry for the newbie question, I'm working with

KnockoutJS
and I am trying to get the base64String value from an observable and store it inside another observable before sending it off.

Why do I need to do that?
Well for some reason when the base64String is passed it has multiple layers to the object which get sent over as NULL.

Any help or suggestion will be appreciated.

var CreateSalesVM = {
UserId: ko.observable(),
Name: ko.observable(),
Phone: ko.observable(),
Email: ko.observable(),
Item: ko.observable(),
Description: ko.observable()


This piece is what I am having the issue with

IMAGETWO: ko.observable({
base64StringArray: ko.observableArray()
}),
IMAGE: ko.computed({
read: function () {
return IMAGETWO().base64StringArray();
},
deferEvaluation: true
}),


/**************\

btnCreateSales: function () {
// IMAGE = this.IMAGETWO().base64StringArray();
console.log("Image text ", this.IMAGE());

//console.log("Host usrl ", urlHostPath);
//console.log("Ko is ", ko.toJSON(this));
$.ajax({
url: urlPath,
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
//console.log("This was a success");
// window.location.href = urlPath + '/';
alert(ko.toJSON(this));
// console.log("Ko is ", ko.toJSON(this));
},
error: function (err) {

//console.log("Ko is ", ko.toJSON(this));
if (err.responseText == "success")
{
//console.log("This was an erro success", urlPath);

// window.location.href = urlPath + '';
}
else {
alert(err.responseText);
// console.log("This was an error ", urlHostPath );
}
},
complete: function () {

}
});
}

};

ko.applyBindings(CreateSalesVM);

Answer Source

IMAGETWO is a method of your VM object. You must specify the object while calling a function, otherwise it will look in a global scope for it. So, you may use either:

IMAGE: ko.computed({
    read: function () {
        return this.IMAGETWO().base64StringArray();
    },
    deferEvaluation: true
}, CreateSalesVM)

or

IMAGE: ko.computed({
    read: function () {
        return CreateSalesVM.IMAGETWO().base64StringArray();
    },
    deferEvaluation: true
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download