How to pass data (selected item) to Durandal composed detail view?

后端 未结 3 1927
忘掉有多难
忘掉有多难 2021-02-08 18:41

I\'ve started using (as of, a few hours ago) Durandal with the hope to manage views and allow composition within a single page - the previous approach, also using Knockout, was

3条回答
  •  执笔经年
    2021-02-08 19:12

    There is a great writeup on how to do this with John Papa's SPA template for Visual Studio by Eric Panorel here: http://ericpanorel.net/blog/hot-towel-spa-master-detail-scenario.

    In short, you can take advantage of routing in Durandal, and it would go something like this:

    master.js will expose a set of items:

    define(function() {
      var self = this;
    
      this.items = ko.observableArray([]);
    
      var activate = function() {
         // ... get your items
         self.items([ { id: 0, name: 'Item 1' }, { id: 1, name: 'Item 2' }]);
      }
    
      return {
        // some properties and ...
        activate: activate
      }
    });
    

    master.html will bind them and link to details view:

    Now, all that remains it to use route data parameter to pull the ID out in the detail viewmodel, detail.js:

    define(function() {
      var self = this;
    
      this.name = ko.observable();
    
      var activate = function(routeData) {
         var itemId = routeData.id;
    
         // ... get your item details
         // var details = ...
    
         self.name(details.name);
      }
    
      return {
        // some properties and ...
        activate: activate
      }
    });
    

    Finally, you will need to specify the route in your main.js:

    define(['durandal/app', 'durandal/viewLocator', 'durandal/system', 'durandal/plugins/router'],
    function(app, viewLocator, system, router) {
    
        //>>excludeStart("build", true);
        system.debug(true);
        //>>excludeEnd("build");
    
        app.title = 'Durandal app';
        app.start().then(function() {
            toastr.options.positionClass = 'toast-bottom-right';
            toastr.options.backgroundpositionClass = 'toast-bottom-right';
    
            //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
            //Look for partial views in a 'views' folder in the root.
            viewLocator.useConvention();
    
            //configure routing
            router.useConvention();
            router.mapRoute('item/:id', 'viewmodels/item', 'Item', false);
    
            app.adaptToDevice();
    
            //Show the app by setting the root view model for our application with a transition.
            app.setRoot('viewmodels/shell', 'entrance');
        });
    });
    

    And there you go!

提交回复
热议问题