Reputation: 1681
How do I amend responseText: self.registrationmark
so that the value of self.registrationmark
evaluates to a variable rather than a string?
e.g. If the value of self.registrationmark
is DE63BEY
then responseText:
should evaluate to the variable DE63BEY
HTML
<input type="text" id="registrationmark" data-bind="value: registrationmark">
Javascript
function ViewModel() {
var self = this;
self.registrationmark = ko.observable();
var DE63BEY = { ... }
var SL64KWX = { ... }
var CU56OHG = { ... }
var VN10YMY = { ... }
var Y926MNB = { ... }
$.mockjax({
url: '/test',
dataType: 'json',
responseTime: 2500,
responseText: self.registrationmark
});
...
}
ko.applyBindings(new ViewModel());
Upvotes: 0
Views: 181
Reputation: 16688
As @sifriday describes, you can define your "variables" as properties of an object, which can be looked up by name. They don't necessarily have to be defined in self
. It can be a separate object:
var responses = {
DE63BEY: { ... },
SL64KWX: { ... },
CU56OHG: { ... },
VN10YMY: { ... },
Y926MNB: { ... }
};
Then
responseText: responses[self.registrationmark()]
If for some reason, you need to define the values as variables, you can use eval
to read their values dynamically. This method is potentially unsafe and shouldn't be used.
responseText: eval(self.registrationmark())
Upvotes: 1
Reputation: 4482
Having just read your comment to Matthew above, I think you first need to set the scope of the variables to this/self:
self.DE63BEY = { ... }
self.SL64KWX = { ... }
self.CU56OHG = { ... }
self.VN10YMY = { ... }
self.Y926MNB = { ... }
Then you must be after:
responseText: self[self.registrationmark()]
ie, call
self.registrationmark()
to get a string like "DE63BEY" and then to get the corresponding variable, you need to look it up within self, as if you were doing:
self["DE63BEY"]
which is of course equivalent to
self.DE63BEY
which is the variable you're after!
Upvotes: 2
Reputation: 12295
Try the following:
$.mockjax({
url: '/test',
dataType: 'json',
responseTime: 2500,
responseText: ko.unwrap(self.registrationmark)
});
Upvotes: 0