knockout.js - How to call a nested function from out side knockout js -
i learning knockout js. still understanding not clear. apologized ask kind of question.
see code first see trying achieve. here jsfiddle link http://jsfiddle.net/tridip/vvdvgnfh/
<button data-bind="click: $root.printproduct()">print product</button> <table id="table1" cellspacing="0" cellpadding="0" border="0"> <tr> <th style="width:150px">product</th> <th>price ($)</th> <th>quantity</th> <th>amount ($)</th> </tr> <tbody data-bind='template: {name: "ordertemplate", foreach: lines}'></tbody> </table> <script type="text/html" id="ordertemplate"> <tr> <td><select data-bind='options: products, optionstext: "name", optionscaption:"--select--", value: product'> </select> </td> <td> <span data-bind='text:price' ></span> </td> <td> <input data-bind='value:quantity' /> </td> <td ><span data-bind='text:subtotal()'></span></td> </tr> </script> var cartline = function () { var self = this; self.products = ko.observablearray(_products); self.product = ko.observable(1); self.price = ko.observable(1); self.quantity = ko.observable(1); self.product.subscribe(function(item){ if(!item) { self.price(0); self.quantity(0); return; } self.price(item.price); self.quantity(item.quantity); }); self.subtotal = ko.computed(function () { return self.price() * self.quantity(); },self); self.printproduct = function() { alert('hello'); } }; var cart = function () { // stores array of lines, , these, can work out grandtotal var self = this; self.lines = ko.observablearray([new cartline()]); // put 1 line in default }; ko.applybindings(new cart());
print product out side button if need call function defined in cartline
how access ? @ possible ?
thanks
you can't call function on cartline outside loop it's outside context (scope), 1 approach can follow have click binding on row, when user clicks row, calls function on root scope save reference selected cartline:
<tr data-bind="click: $root.selectrow"> <td><select data-bind='options: products,
and cart function has selectrow , print functions:
var cart = function () { // stores array of lines, , these, can work out grandtotal var self = this; self.lines = ko.observablearray([new cartline()]); // put 1 line in default self.selectrow = function(line) { self.selected = line; } self.print = function() { if(self.selected) { self.selected.printproduct(); } } };
then print button calls print function on root delegates selected cartline
<button data-bind="click: $root.print">print product</button>
here update jsfiddle http://jsfiddle.net/omerio/vvdvgnfh/1/
Comments
Post a Comment