Skip to content Skip to sidebar Skip to footer

Variable Dependency With Knockoutjs

I'm building an application with KnockoutJS with a component that essentially acts as a sequential spreadsheet. On different lines users may define variables or use them to repres

Solution 1:

I would be tempted to use a publish/subscribe model, using something like Peter Higgins' PubSub jquery plugin

Your overall app would subscribe/listen out for lines publishing an event that they have a variable definition. This would store any variable names in a standard javascript hashtable, along with the value. When a variable found event is published by a line, the app would check through all the known variables, and if it finds that it is a change to an existing variable value, it would publish a variable changed event. All the lines would subscribe to that event. They can then check whether they have a variable matching that name, and update the value accordingly.

Here's some untested code to give you an idea of what I mean:

var app = function()
{
    varself = this;

    self.variables = {};
    $.subscribe('/variableAssigned', function (key, value)
        {
            // I think that this is the best way of checking that there is a variable// in the objectif(self.variables.hasOwnProperty(key))
            {
                if(self.variables[key] !== value)
                {
                    $.publish('/variableChanged', [ key, value ]);
                }
            }
        });
}

In your Line object:

$.subscribe('/variableChanged', function (key, value)
    {
        // loop through varMap and see if any of them need updating.
    });

Post a Comment for "Variable Dependency With Knockoutjs"