2

就像是 :

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

像......这是不正确的:

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

这甚至是正确的方法吗?在尝试从 jquery 转换之前,我应该建立控制器和模型吗?

更多细节:

我正在尝试重写connectPeerJS 示例中的函数: https ://github.com/peers/peerjs/blob/master/examples/chat.html

4

2 回答 2

3

如果您的事件侦听器类似于 websockets,则事件发生在 Mithril之外,这意味着您需要自己管理重绘。这是你需要做的:

  1. 将数据存储在独立模型中
  2. 在渲染 Mithril 视图时使用该模型
  3. open活动中,更新您的模型,然后调用m.redraw()

概念示例:

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()
})
于 2015-05-26T17:09:03.810 回答
2

在 Mithril 中,你不应该尝试直接接触 DOM。您的事件处理程序应修改 View-Model 的状态,该状态应在您的 View 方法中访问。如果您发布更多代码,我可以更详细地解释它是如何组合在一起的。

这是一个简单的示例,显示了流经秘银的数据。您的情况需要更复杂,但我目前无法解析所有 peer.js 代码。

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);

请注意,该按钮正在调用 View-Model ( set) 上的方法,该方法正在设置属性 ( vm.description) 的值。这会导致 View 重新渲染,并且 div 显示新值 ( m("div", demo.vm.description()))。

于 2015-05-26T16:03:41.310 回答