Jeff L
Jeff L

Reputation: 23

knockoutjs - observableArray of objects with viewable observable values

I am using KnockoutJS to write a small application where a user can edit a "product" by typing in text to input fields that will automatically update viewable text boxes on top of an image. This allows the user to preview engravable lines before purchasing for instance a Plaque.

So here is my problem:

I have an object (product) that holds an observableArray (product.lines):

self.product = ko.utils.arrayMap(jsonData, function(data) {
    return new CustomizableProduct(
    data.sku, data.name, data.lines, data.fonts, data.plates)
});
function CustomizableProduct(sku, name, lines, fonts, plates) {
  return {
    sku: ko.observable(sku),
    name: ko.observable(name),
    lines: ko.observableArray(lines),
    fonts: ko.observableArray(fonts),
    plates: ko.observableArray(plates)
  }
}

jsonData:

var initialData = [
{
"sku": "PMW",
"name": "Premium Genuine Walnut Step Edge Plaque",
"plates": [
    {
    "sku": "plateSKU",
    "name": "plateName",
    "img": "/images/plates/plateSKU.jpg"},
{
    "sku": "plateSKU2",
    "name": "plateName2",
    "img": "/images/plates/plateSKU.jpg"}
],
"lines": [
    {
    "label": "Line 1",
    "value": "Line 1",
    "type": "input",
    "characterLimit": "146"},
{
    "label": "Line 2",
    "value": "Line 2",
    "type": "input",
    "characterLimit": "156"},
{
    "label": "Line 3",
    "value": "Line 3",
    "type": "submit",
    "characterLimit": "176"}
],
"fonts": [
    {
    "font": "Times New Roman"}
]}
];

product.lines is looped and creates input boxes with its default value set from the object (value: $data.value). these input boxes are editable by the user. I also need to display the value of the input box as its updated sort of to act as a preview of what is being typed. When I type in a new word it updates in the object but the field that needs to display the value does not update.

I have a jsFiddle of my code here: http://jsfiddle.net/pR6xp/2/

What do I need to write to get that value to update when its updated by editing the input field?

Thanks..

Upvotes: 2

Views: 1746

Answers (1)

madcapnmckay
madcapnmckay

Reputation: 15984

You create an observableArray of lines but when objects are added to an observableArray their properties do not become observable, this is left upto you to implement.

I added a ProductLine object with an observable value and initialized the lines collection with these objects.

http://jsfiddle.net/vRBhP/1/

Hope this helps.

Upvotes: 2

Related Questions