user2749007
user2749007

Reputation: 21

dynamically add a durandal widget

What is the process of adding a widget to a page dynamically? Essentially I have an "Add Widget" button on a view which is hooked up to a function addWidget() in the viewmodel. Basically, when someone hit's the button, I want to dynamically create an instance of a durandal widget and add it to the DOM. My code looks like this:

    var addWidget = function () {

        var parent = $('<div></div>')
            .attr('data-bind', 'widget: { kind:\'myWidget\'}')
            .appendTo($('#dashboardContent'))
            .get(0);

        return widget.create(parent, { id: 'Hello World' });
    }

I can see in the browser developer tools that the widget HTML (view) is added to the DOM, but it's not rendering the widget, and activate is not being called on the widget.

What am I missing?

Upvotes: 2

Views: 700

Answers (1)

PW Kad
PW Kad

Reputation: 14995

From the looks of it you are trying to use jQuery to add the widget to the DOM. Just thinking out loud the problems are that A: jQuery has no idea what activate is (that is handled by Durandal's router) and B: Nothing will get bound properly. If you are trying to add widgets, why not create an observableArray that contains widgets and just add them into there? That may sound a bit silly, and I am not sure the best way to approach it, but basically it could look like this

In your view model -

var myWidgets = observableArray();
myWidgets.push(someObjectsToComposeTheWidget);

And in your view -

<ul data-bind="foreach: myWidgets">
     <li data-bind="widget: {kind:'yourWidget', items: somethingGoesHere, headerProperty:'name'}">/div>
<ul>

This will allow you to dynamically add and display the widgets without having to get messy and use jQuery to display things.

Upvotes: 1

Related Questions