3. Pass values to the class constructor

Now we'll start adding elements to our very simple custom view. In this example, we'll show how you can pass values to your view in different ways—when instantiating the view from the Simple XML extension and by using the options dictionary (values to initialize the view).

  1. Open customview.js and replace the code with the following, which contains a new "propA" property:
  2. /* customview.js */
    
    require([
        "/static/app/customviewtutorial/demoview.js",
        "splunkjs/mvc/simplexml/ready!"
    ], function(DemoView) {
    
        // Create a custom view
        var customView = new DemoView({
            id: "mycustomview",
            propA: "valA",
            el: $("#mycustomview")
        }).render();
    
    });
  3. Open demoview.js and replace the code with the following:
  4. /* demoview.js */
    
    define(function(require, exports, module){
        // Base class for custom views
        var SimpleSplunkView = require('splunkjs/mvc/simplesplunkview');
    
        // Define the custom view class
        var DemoView = SimpleSplunkView.extend({
            className: "demoview",
    
            // Extend the options and provide initial values
            options: {
                propB: "valB"
            },
    
            // Override the render function to make the view do something
            // In this example: print to the page and to the console
            render: function() {
    
                // Print the variables to the page
                this.$el.html("propA: " + this.settings.get("propA") +
                    "<br>propB: " + this.settings.get("propB"));
                
                // Print the variables to the console
                console.log("propA is: ", this.settings.get("propA"));
                console.log("propB is: ", this.settings.get("propB"));
    
                return this;
            }
        });
        return DemoView;
    });

    Here's what this code does:

    • The options dictionary has been overridden with our "propB" property.
    • The render method now displays the values of our two new properties, both on the page and in the console.
  5. Save your changes.
  6. Refresh Splunk Web by opening the http://<localhost:port>/debug/refresh URL in your web browser and clicking Refresh.
  7. Navigate to the dashboard, http://<localhost:port>/app/customviewtutorial/custom_view. You should see the two properties, propA and propB:
  8. PropA and PropB

Continue to 4. Add a search to the view and display data from it.