Knockout: passing the current object to the method through the user element

I have a custom html element (button) to which I pass a method. This is then done by knocking out the user element. The problem is that I need to access the current object in the array. I achieved this like this:

ko.components.register('custom-element', {
    viewModel: function(params) {

      this.nestedMethod = function (){
        //this line feels dirty
        var parameter = ko.contextFor(arguments[1].target).$parent;
        params.method(parameter);
      }
    }, 
    template:
    '<button data-bind="click: nestedMethod">remove item</button>'
});

It seems very hacked and potentially prone to hacking. Is there a better way to achieve this? Here is a link to a working example:

http://liveweave.com/w0L5w5

+4
source share
2 answers

Knockout , , .

, bindingContext params.

( HTML):

<custom-element params="method: $parent.removeItem, bindingContext: $context" />

JS:

viewModel: function(params) {
  this.nestedMethod = function (){
    var bindingContext = params.bindingContext;

    // @access using the following:
    // var rootVm = bindingContext.$root;
    // var currentData = bindingContext.$data;
    // var parentData = bindingContext.$parent;

    var parameter = ko.contextFor(arguments[1].target).$parent;
    params.method(parameter);
  }
},
+1

, , , .

HTML:

<!-- Note the () in the binding!!! -->
<custom-element params="click: clickHandler()"></custom-element>

JS:

var ParentView = function(message) {
    var self = this;

    self.message = message;

    self.clickHandler = function() {
        return function() {
            alert(self.message);
        }
    }
}

ko.components.register('custom-element', {
    viewModel: function(params) {
        var self = this;

        self.nestedMethod = function() {
            params.click();            
        };
    }, 
    template:  '<button data-bind="click: nestedMethod">remove item</button>'
});

ko.applyBindings(new ParentView("Hello, Knockout!"));

JSFiddle

0

All Articles