javascript - How should my objects be structured for proper MVVM in Knockout? -


i'm working knockout , trying stay true mvvm structure , trying make objects have dependency on each other.

here have, gentle, i'm still learning this:

model, viewmodel, service definitions:

var app = window.app || {};  (function(ns, $, ko) {     ns.models = {};     ns.viewmodels = {};     ns.services = ns.services || {};      //service def     ns.services.searchservice = function() {         this.searchbyname = function(name, callback) {             $.get("/api/searchbyname/" + name, function(d){                 callback(d);             });         };     };      //model def     ns.models.searchresultmodel = function(json) {         var self = this;          ko.mapping.fromjs(json, {}, self);     };      //viewmodel def     ns.viewmodels.searchresultsviewmodel = function() {         var self = this;          self.dataservice = new ns.services.searchservice();         self.searchresults = ko.observablearray();          self.getsearchresultsbyname = function(name){             self.dataservice.searchbyname(name, function(d) {                 $.each(d, function(i, e) { self.searchresults.push(new ns.models.searchresultmodel(e)); });             });         };     }; }(app, jquery, ko)); 

and can use so:

var vm = new app.viewmodels.searchresultsviewmodel();  vm.getsearchresultsbyname("doe");  ko.applybindings(vm, document.getelementbyid("search-results-form")); 

this starting point , seems ko.applybindings(...) should in viewmodel somewhere.

with that, going right direction or off it?

nothing unusual looking. it's hard question answer because if there isn't you're doing wrong, there's not say...

one thing noticed that

$.get("/api/searchbyname/" + name, function(d){     callback(d); }); 

should replaced with

$.get("/api/searchbyname/" + escape(name)).done(callback); 

the name should escaped because might contain invalid url characters, , there's no reason wrap callback. (in general, expression function (x) { f(x) } adding unnecessary indirection simpler expression f.)

in getsearchresultsbyname function, name more descriptive d good, since you're being verbose naming elsewhere.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -