knockout.js - Cannot map function in view model with json data knockout mapping -
my viewmodel this:
var viewmodel = function(){ var self = this; self.title = ko.observable('hello world'); self.rows = ko.observablearray(); self.on_click = function(){ alert('hello world'); var data = [ { id : 1, x : 1, y : 2, z : 3, }, { id : 2, x : 4, y : 5, z : 6, }, { id : 3, x : 7, y : 8, z : 9, } ]; self.rows(ko.unwrap(ko.mapping.fromjs(data, viewmodelrow))); alert(self.rows()); }; }; var viewmodelrow = function(){ var self = this; self.id = ko.observable(); self.x = ko.observable(); self.y = ko.observable(); self.z = ko.observable(); self.mthd = function(){ alert('just clicked'); }; }; vm = new viewmodel(); ko.applybindings(vm);
my html this:
<body> <h1 data-bind="text:title"></h1> <div data-bind="foreach: rows"> <table> <tr> <td data-bind="text : id"></td> <td data-bind="text: x"></td> <td data-bind="text: y"></td> <td data-bind="text: z"></td> <td><button type="button" data-bind="click: mthd">btn</button></td> </tr> </table> </div> <button type="button" data-bind="click: on_click">button</button> </body>
when mapping performed data on viewmodelrow view model throws error saying
referenceerror: mthd not defined
i want json data mapping viewmodelrow along method named mthd define in viewmodelrow. please help. jsfiddle link: http://jsfiddle.net/enabqm3d/5/
you using mapping plugin in wrong way. fromjs
function takes 3 arguments:
fromjs(data, mappingdefinition, mappingtarget);
the mappingdefinition
defines rules should executed during mapping, example, create objects data, shown here:
var viewmodel = function(){ var self = this; self.title = ko.observable('hello world'); self.rows = ko.observablearray(); self.init = function(){ var data = { rows: [ {id : 1, x : 1, y : 2, z : 3,}, {id : 2, x : 4, y : 5, z : 6,}, {id : 3, x : 7, y : 8, z : 9,} ] }; ko.mapping.fromjs(data, { rows: { create: function (options) { return new viewmodelrow(options.data); } } }, self); }; }; var viewmodelrow = function(data){ var self = this; // think whether these properties need observable self.id = ko.observable(data.id); self.x = ko.observable(data.x); self.y = ko.observable(data.y); self.z = ko.observable(data.z); self.mthd = function(){ alert('just clicked ' + self.id() ); }; }; var vm = new viewmodel(); ko.applybindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script> <h1 data-bind="text:title"></h1> <div data-bind="foreach: rows"> <table> <tr> <td data-bind="text: id"></td> <td data-bind="text: x"></td> <td data-bind="text: y"></td> <td data-bind="text: z"></td> <td><button type="button" data-bind="click: mthd">btn</button></td> </tr> </table> </div> <button type="button" data-bind="click: init">init viewmodel</button>
read through the documentation, it's not lot read.
Comments
Post a Comment