Search code examples
mvvmbreezedurandalcompositiondurandal-2.0

durandal : multiple views for one viewmodel


Im working with durandal 2 and breezejs.

I have some tables in my DB lets call them table1 and table2.

In the project i created a CRUD for table1 : viewmodels/table1crud.js + views/table1crud.html viewmodel and view that will connect to the DB using breeze, get data from table1, list the data, and offer a update/delete/add operations.

For table2 i can do the same, create another crud (view/viewmodel), BUT it can be not elegant, specially if i have more than 2 tables.

So my idea is to create ONE entitycrud viewmodel, with a constructor:

define(function(require){

   var vm= function(entityType){

    this.entityType= entityType;
    this.activate = function(){...};
    this.attached = function(){...};
    etc ...

    this.createEntity = function(){...};
    etc ...
   };

  return vm;
 });

Plus multiple views views/table1.html and views/table2.html.

So here is my question : is there any way to compose entitycrud with table1 or table2 using the entityType in the constructor ?

Something like :

<div data-bind="compose : {model : 'entitycrud("table1")', view : 'views/table1'}"></div>

<div data-bind="compose : {model : 'entitycrud("table2")', view : 'views/table2'}"></div>

This html code will not work of course, how can i do something similar ??

Thank you.


Solution

  • You can have a properties in another view model with the correct values like this (let's say cruds model) ,

    define(function(require){
    
       var vm= function(entityType){
             this.crudTable1=new entitycrud("table1");
             this.crudTable2=new entitycrud("table2");
       };
    
        return vm;
     });
    

    and then do the compose binding like this inside the cruds.html view,

      <div data-bind="compose : {model : crudTable1, view : 'views/table1'}"></div>
    
    <div data-bind="compose : {model : crudTable2, view : 'views/table2'}"></div>