如何用秘银等效替换jquery?

时间:2015-05-26 15:56:37

标签: javascript jquery mithril.js

类似的东西:

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

有类似......这是不正确的:

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

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

更多详情:

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

2 个答案:

答案 0 :(得分:3)

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

  1. 将数据存储在独立模型中
  2. 在渲染Mithril视图时使用该模型
  3. open事件中,更新您的模型,然后致电m.redraw()
  4. 概念示例:

    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()
    })
    

答案 1 :(得分:2)

在秘银中,你不应该试图直接触摸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()))。