0

I'm trying to solve the following problem using Knockout JS

  • Need to bind a HTML form via "submit" binding to a child view model
  • The call back method bound to "submit" is an inherited method

The following code will explain the above scenario better. The same can be found in this fiddle.

function MasterViewModel() {
    var self = this;
    self.employeeViewModel = new EmployeeViewModel();
};

function EmployeeViewModel () {
    var self = this;
    self.empFirstName = ko.observable();
    self.empLastName = ko.observable();
    self.employeeList = ko.observableArray([]);
};

EmployeeViewModel.prototype.addEmployee = function () {
    var self = this;
    self.employeeList.push(new Employee(self.empFirstName(), self.empLastName()));
}

function Employee(firstNameParam, lastNameParam) {
    var self = this;
    self.firstName = ko.observable(firstNameParam);
    self.lastName = ko.observable(lastNameParam);
}

ko.applyBindings(new MasterViewModel());

In HTML, I use the submit binding as shown below;

<form data-bind="submit: employeeViewModel.addEmployee">
</form>

I've observed that always, the "this" context passed for the callback method is an instance of "MasterViewModel". I searched for a method of passing a different context with the "submit" binding, but in vain.

Is this a limitation that I'm trying to exploit, of is there a workaround?

Thanks.

4

1 回答 1

0
 <script type="text/javascript">
       var viewModel = {       
           numberOfClicks : ko.observable(0),       
           incrementClickCounter : function() {  
                 var previousCount = this.numberOfClicks(); 
                 this.numberOfClicks(previousCount + 1);    
            }  
       }; 
   </script>

http://knockoutjs.com/documentation/click-binding.html 根据敲除文档,如果您还没有,您应该在脚本中定义增量 Click Counter 函数,这是您可以控制“this”值的地方

于 2013-03-18T11:33:12.303 回答