1

I have a Knockout observable array that I wish to edit from within Javascript and from the HTML as well. Here is my code:

var ListModel = function(formula) {
  var self = this;
  self.formula = ko.observableArray(formula);

  this.mergeEquation = function(op) {
    if (op.type == "ins") {
      self.formula.splice(op.position, 0, op.value);
    } else if (op.type == "del") {
      self.formula.splice(op.position, 1);
    } else {
      console.info("No match: " + op.value + op.position);
    }
  };
};

My variable op is a JSON string. I know how to call the mergeEquation function using HTML data-bind, but how do I do so from within the same JS file? My current code goes something like this:

ko.applyBindings(new ListModel(formula));
//...
//initializing of JSON object called op
//...
if (something) {
  mergeEquation(op);
}

but it doesn't work. Am I missing out some step here? I've read up on functions and extenders but both seems too overkill for what I'm trying to do here.

PS: Here's a sample of the JSON structure I'm working with:

{"type":"ins", "clientID":1223, "version":0, "value":"hi", "position":0, "id":2736}
2
  • you need to show the part where you create the ListModel, and where you try to call mergeEquation in relation to it :) Commented Jun 11, 2012 at 3:08
  • Oh right. I'll edit my post to make it clearer. Commented Jun 11, 2012 at 3:11

1 Answer 1

3

change :-

ko.applyBindings(new ListModel(formula));

to

  var vm = new ListModel(formula);
   ko.applyBindings(vm);

so, now vm is the thing you can call the mergeequation on

vm.mergeEquation(op)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.