Teo
Teo

Reputation: 125

Knockout JS passing parameter to function

I'm working on Durandal project and i need to know the best way to call a function passing parameters from the HTML side. In the previous versions I used always the way:

<div data-bind="foreach: rows">
 <div data-bind="visible: $root.myFunction.bind($data,'parameter')">
  ...
  ...
 </div>
</div>

But in this case in the Js side, in my function i receive only the main objects: I can't receive my ROW data and I can't receive the 'parameter' value! This is my model in the js side:

define(['services/datacontext', 'durandal/app', 'config'], 
 function (datacontext, app, config) {
   var model = function () {
      var self = this;
      ...
      ...
      ...
   }

   model.prototype.myFunction(parameter) {
      var show = false;
      ...
      ...
      return show;
   }

   return model;
}

Can you help me?

Upvotes: 1

Views: 2924

Answers (2)

Jeff
Jeff

Reputation: 12163

You can access your $data as this within your myFunction - the first parameter to .bind sets the context (context = the object that this refers to).

   model.prototype.myFunction(parameter) {
      var show = false;
      // `this` is the $data you specified in your view
      return show;
   }

Upvotes: 1

Stefan
Stefan

Reputation: 14863

You can use a funciton expression:

<!-- function expression -->
<div data-bind="click: function (data) { myFunction('param1', data) }">...</div>

this way you avoid passing only one parameter.

Example:

<p>Test</p>
<div data-bind="foreach: test">
    <button data-bind="click: function (data) { myFunction('param1', data) }">Test</button>
</div>

ko.applyBindings({
    test: [{
        myFunction: function (param1, data) {
            alert(param1 + " " + data.data);
            debugger;
        },
        data: "test1"
    }, {
        myFunction: function (param1, data) {
            alert(param1 + " " + data.data);
        },
        data: "test2"
    }]
});

Fiddler: http://jsfiddle.net/9AZjN/

Upvotes: 0

Related Questions