Frage

I've got a web project, where I need to model some basic JavaScript classes and put them into a separate javascript file. Now I want to use them locally on a page and add them into a master view model, which acts as binding object. My question is, how do you realize the connections between model class and master view model?

This is the class model from the api:

Namespace.Problem = function()
{
    var self = this;

    self.identifier = ko.observable();
    self.summary = ko.observable();
    self.title = ko.observable();
};

Namespace.Problem.withJson = function(json)
{
    var problem = new Namespace.Problem();

    problem.identifier(json.identifier);
    problem.summary(json.summary);
    problem.title(json.title);

    return problem;
};

and here the master view model:

function MasterViewModel()
{
    var self = this;

    self.problem = ko.observable({});

    self.loadData = function()
    {
        // Load data via jQuery.getJson();
        self.problem(Namespace.Problem.withJson(json));
    }
}

I leave the applyBindings function out of the code here.

Is it the right way to have an attribute in the master view model, which looks like this above, or should it be like

self.problem = new Namespace.Problem();

Are the model properties of the api class set the right way, too? Or is the following better?

self.identifier;
self.summary;
self.title
War es hilfreich?

Lösung

First of all, take a look on:

Often a MainViewModel aggregates child view models and changes one view model to another thru observable binding.

The easest way and more convenient do apply binding on document ready event

For example:

viewModelFactory = function() {
    function MainViewModel(){
        var self = this;

        self.items = ko.observableArray([
            new Page1(),
            new Page2()
        ]);
        self.selectedPage = ko.observable(self.items()[0]);
        self.onSelected = function(page){
            self.selectedPage(page);       
        };
    }

    function PageViewModel(templateName, linkName){
        var self = this;
        self.templateName = templateName;
        self.linkName = linkName;
    }

    function Page1(){
        var self = this;
        $.extend(self, new PageViewModel('template1', 'Page1'));        
        self.data = 'blablabla-blablabla';
    }

    function Page2(){
        var self = this;
        $.extend(self, new PageViewModel('template2', 'Page2'));

        self.people = [
            { name: 'Paul', age: 18, gender: 'male' },
            { name: 'John', age: 25, gender: 'male' },
        ];
    }

    return {
        create: function(){
            return new MainViewModel();
        }
    };
}();

$(function(){
    var mainViewModel = viewModelFactory.create();
    ko.applyBindings(mainViewModel);
})

Here's full sample

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top