Pregunta

I have a dozen of templates, each requires an event handling that looks like

event: { 
 vclick: function (data, event) { 
  $parents[1].cellClick($parents[1].rows()[$parentContext.$index()], data, event) 
    } 
}

How can I make this shorter and better to handle? I tried moving the event handler into the viewmodel, but I am having troubles passing around the binding context properties ($parents etc.)

Edit: there was a missing $ in $parentContext.$index() and this is the cellClick code, it really does nothing special:

self.cellClick = function (row, data, event)
{
    var rowData = self.getRowObject(row.Items());
    var cellData = rowData[data.Key()];
    self.rowClickHandler(cellData, rowData, event);
    return true;
}
¿Fue útil?

Solución

You could move it to your viewmodel if you pass the parent and its index:

vclick: function(data, evt) { 
    $root.vclick(data, event, $parents[1], $parentCountext.index()); 
}

Then in your viewmodel it might look like this:

self.vclick = function(data, event, parent, rowIndex) {
    parent.cellClick(parent.rows()[rowIndex], data, event);
};

But this does not feel right. If you could share some more code (cellClick?), we can determine whether there's a better approach.

Otros consejos

You can try this binding:

event: { mouseover: $parents[1].myOver.bind($data, $parentContext, $parents[1]) }

With the function myOver in your item's grand-parent's model:

this.myOver = function (parentContext, parents1) { 
    alert("Data: " + JSON.stringify(parents1)); 
}

In which you will be able to access $parentContext with variable parentContext, $parents[1] with parents1 and your item's binding ($data) with this.

See this example: jsFiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top