Monday, 15 June 2015

javascript - Knockout.js 2.2.1 can't find observable array -



javascript - Knockout.js 2.2.1 can't find observable array -

not sure what's going wrong here, knockoutjs having issues finding observable array that's within masterviewmodel. using 2.2.1 jquery 1.8.x not first kjs app. here is:

initialize

$(function() { window.vm = new masterviewmodel(); ko.applybindings(vm); });

viewmodel

function masterviewmodel(data) { var self = this; self.currentappview = ko.observable(); // users self.userlist = ko.observablearray([]); self.templatelistgetter = ko.computed(function() { $.getjson("/user/list"), function(data) { var mapped = $.map(data, function(item) { homecoming new usermodel(item) }); self.userlist(mapped); }; }); self.gotoappview = function(appview) { location.hash = '!/' + appview; }; sammy(function() { this.get('#!/:appview', function() { self.currentappview(this.params.appview); $('.appview').hide(); ko.applybindings(new window[this.params.appview+'vm']()); }); this.notfound = function(){ location.hash = "!/dashboard"; } //this.raise_errors = true; }).run(); }

the view

<table class="table table-bordered table-striped"> <tbody data-bind="foreach: userlist"> <tr> <td data-bind="text: guid"></td> <td data-bind="text: firstname"></td> <td data-bind="text: lastname"></td> <td data-bind="text: email"></td> <td data-bind="text: updated"></td> <td data-bind="text: suspended"></td> </tr> </tbody> </table>

i have simple table loading

even after double-checking couple things adding defer="defer" js tag , ensuring userlist exists, cannot find observablearray. gives error:

message: referenceerror: userlist not defined; bindings value: foreach: userlist error {}

anyone have thought what's going on?

update

for wondering gets called every time hash changes:

function usersvm() { // info var self = this; // behaviours $('#users').show(); }

it looks you're initializing knockout undefined viewmodel?

ko.applybindings(new window[this.params.appview+'vm']());, yet actual viewmodel window.vm. case sensitivity ftw. also, viewmodel on window created / initialized. don't need new operator.

so, alter applybindings line be

ko.applybindings(window[this.params.appview+'vm']());

updated answer: poster

there no necessity maintain running ko.applybindings every time route changed since applying bindings on page load. sammy.js changed to:

sammy(function() { this.get('#!/:appview', function() { self.currentappview(this.params.appview); $('.appview').hide(); window[this.params.appview+'route'](); }); this.notfound = function(){ location.hash = "!/dashboard"; } //this.raise_errors = true; }).run();

it ko.computed or regular function phone call window.vm.getuserlist() isn't running properly, saved different question.

function usersroute() { // info var self = this; // behaviours $('#users').show(); window.vm.getuserlist(); }

javascript mvvm knockout.js knockout-2.0

No comments:

Post a Comment