I'm working with knockout and am trying to stay true the MVVM structure and trying to make the objects have that dependency on each other.

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){

    //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 I can currently use it like so:

var vm = new App.ViewModels.SearchResultsViewModel();


ko.applyBindings(vm, document.getElementById("search-results-form"));

This is just my starting point and it seems like the ko.applyBindings(...) should be in the ViewModel somewhere.

With all that, am I going the right direction for this or am I completely off with it?


This looks good me, just as it looked good for the SO reviewers.

Some thoughts;

  • Consider 'use strict';
  • Consider naming your anonymous functions
  • It is not clear how SearchResultModel deals with failed calls
  • var self = this; is only needed for closures, you don't need it in ns.Models.SearchResultModel

All in all, pretty solid.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.