javascript - Instantiate ViewModel from array items within an existing ViewModel. -
i've started messing knockout (tech requirement) , i'm trying build gallery custom functionality.
the data coming json
response represents 1 gallery (title, description, etc) , within gallery object, array of slides.
to try , separate concerns i'd love have gallery-based viewmodel , separate slide viewmodel.
but i'm not sure how instantiate slide viewmodel on array within object.
in earlier version tried loop on array of slides not sure how i'd physical execute i'm trying set new instance of slideviewmodel on each slide
object in slides
array
any appreciate. codepen here: http://codepen.io/pbj/pen/maolmb
code here:
js
var testgallery = { "title" : "anna's gallery title", "slides" : [ { "title": "slide image #1", "image" : "http://google.com/image/goes/here" }, { "title": "slide image #1", "image" : "http://google.com/image/goes/here" }, { "title": "slide image #1", "image" : "http://google.com/image/goes/here" }, { "title": "slide image #1", "image" : "http://google.com/image/goes/here" }, ] } function galleryviewmodel(data) { // gallery functions this.title = ko.observable(data.title); } function slideviewmodel() { // slide functions here this.name = ko.observable(data.slides.title); } var gallery = new galleryviewmodel(testgallery); ko.applybindings(gallery);
you should creating child function of slide
achieve looking @ .
viewmodel:
function galleryviewmodel(data) { var self = this; self.title = ko.observable(data.title); self.caption = ko.observable(data.caption); self.slides = ko.observablearray(); self.totalslides = ko.observable(data.totalslides); self.slides($.map(data.slides, function (n) { //mapping child function in here return new slide(n); })) } function slide(data) { //child function this.title = ko.observable(data.title); this.image = ko.observable(data.image); this.position = ko.observable(data.position); } var gallery = new galleryviewmodel(annasgallery); ko.applybindings(gallery);
working sample here grabs
you can take of mapping plugin other way in single line(as per code)
code:
ko.applybindings(ko.mapping.fromjs(annasgallery));
check sample here using mapping plugin
ps: far see nothing editable can bind plane js array view (unnecessary usage of observable turn costly )
Comments
Post a Comment