Search code examples
javascriptbackbone.jshandlebars.jsmaterial-design-lite

Register MDL components


I'm using backbone with handlebars templates on the frontend along with MDL.

For example I want to integrate the demo dropdown menu. Since it will be loaded at later point (not on page load), the dropdown is not working.

<button id="demo-menu-lower-right" 
        class="mdl-button mdl-js-button mdl-button--icon">
       <i class="material-icons">more_vert</i>
</button>

<ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect"
    for="demo-menu-lower-right">
       <li class="mdl-menu__item">Some Action</li>
       <li class="mdl-menu__item">Another Action</li>
       <li disabled class="mdl-menu__item">Disabled Action</li>
       <li class="mdl-menu__item">Yet Another Action</li>
</ul>

According to getting started I need to register components if they are dynamic.

My backbone view looks like this

(function () {
'use strict';
var $ = require('jquery'),
    hbs = require('handlebars'),
    Backbone = require('backbone');

var menuTPL = require('nav/navigation-links.hbs');

module.exports = Backbone.View.extend({
    el: $('.mdl-navigation'),
    initialize: function () {
        this.render();
        this.listenTo(this.model, 'change', this.render);
    },
    render: function () {
        var template = menuTPL({user: this.model.toJSON()});
        this.$el.html(template);
    },
});
})();

Now where exactly would I register this component and what would be reasonable approach to this so I don't have to write same code over and over again to register new stuff since almost all the page is being templated? CSS rules are applied ofc, it is just javascript not working on those components.

I'm kinda lost where to even start here, so any suggestion or answer is welcomed.

So far I've figured out that I can call componentHandler.upgradeAllRegistered(); and all of them will be registered and working properly. I could hook up this on event after renders, but not sure about performance of this. To my understanding this will go through whole DOM.

Also, I would like to avoid registering one by one or as an array since that is error prone and maintenance nightmare.

My next step will be to look if I can limit the upgradeAllRegistered to specific scope (el from backbone) so I can only target parts of the page which are being changed by the view.


Solution

  • Try...

    componentHandler.upgradeElements(rootElement);

    At least that's working for me after I add elements to a dialog box.