2

Something like :

peer.on('open', function(id){ // this is a non jquery event listener 
  $('#pid').text(id);
});

With something like...this is not correct:

peer.on('open', function(id){
  m('#pid',[id])
});

Is this even the right approach? Should I be establishing a controller and model before I attempt to convert from jquery?

More details:

I am trying to rewrite the connect function in the PeerJS example: https://github.com/peers/peerjs/blob/master/examples/chat.html

Community
  • 1
  • 1
jmunsch
  • 22,771
  • 11
  • 93
  • 114

2 Answers2

3

If your event listener is something like websockets, then the event happens outside of Mithril, which means you need to manage redrawing yourself. This is what you'll need to do:

  1. Store your data in an independent model
  2. Use that model when rendering your Mithril view
  3. On the open event, update your model, then call m.redraw()

Conceptual example:

var myModel = { id: 'blank' }

var MyComponent = {
  view: function () {
    return m('#pid', myModel.id)
  }
}

m.mount(document.getElementById('app'), MyComponent)

// This happens outside mithril, so you need to redraw yourself
peer.on('open', function(id) {
  myModel.id = id
  m.redraw()
})
soundly_typed
  • 39,257
  • 5
  • 28
  • 36
2

In Mithril, you should not try to touch the DOM directly. Your event handler should modify the View-Model's state, which should be accessed in your View method. If you post more code, I could give a more detailed explanation of how it pieces together.

Here is a bare-bones example that shows the data flowing through Mithril. Your situation will need to be more complicated but I'm not currently able to parse through all of that peer.js code.

http://codepen.io/anon/pen/eNBeQL?editors=001

var demo = {};

//define the view-model
demo.vm = {
  init: function() {
    //a running list of todos
    demo.vm.description = m.prop('');

    //adds a todo to the list, and clears the description field for user convenience
    demo.vm.set = function(description) {
      if (description) {
        demo.vm.description(description);
      }
    };
  }
};

//simple controller
demo.controller = function() {
  demo.vm.init()
};

//here's the view
demo.view = function() {
  return m("html", [
    m("body", [
      m("button", {onclick: demo.vm.set.bind(demo.vm, "This is set from the handler")}, "Set the description"),
      m("div", demo.vm.description()) 
    ])
  ]);
};

//initialize the application
m.module(document, demo);

Notice that the button is calling a method on the View-Model (set), which is setting the value of a property (vm.description). This causes the View to re-render, and the div to show the new value (m("div", demo.vm.description())).

Brandon Horst
  • 1,921
  • 16
  • 26