ConflictBoy
ConflictBoy

Reputation: 35

Mithril.js - getScript

I'm trying add component Eshop_pane" to some div. Component Eshop_panel is in another external script, so I add this part of script with $.getScript, but this component won't show up. Can you help me?

m("div.fr", [
    m("div", {class: ctrl.uid}),
    $.getScript("some_panel.js").done(function(script) {
       m.component(Eshop_panel, {})
    })
])

//some_panel.js
var Eshop_panel = {
    view: function() {
        return [
            m("div", "Hello world!"),
        ]
    }
};

Upvotes: 1

Views: 237

Answers (1)

Bryce
Bryce

Reputation: 401

One option would be to load the script before any of the relevant code is actually executed, eg:

$.getScript("some_panel.js").done(function(script) {
  m.mount(someElem, { // Ie, don't actually do the mount until everything's ready
    view: function() {
      return m("div.fr", [
        m("div", {class: ctrl.uid}),
         m.component(window.Eshop_panel, {})
        })
      ])
    }
  })
})

Or another option could be to display a placeholder until the script has loaded:

$.getScript("some_panel.js").done(function(script) {
  m.redraw()    
})
...
m("div.fr", [
    m("div", {class: ctrl.uid}),
    typeof window.Eshop_panel === 'undefined' ? 'Loading...' : m.component(Eshop_panel, {})
])

(I'd suggest considering investigating tools like AMD or Browserify (etc) to help with this type of scenario. i.e. I wouldn't do it this way personally, but it might be the simplest option for what you're trying to achieve.)

Upvotes: 0

Related Questions