Skip to content

Instantly share code, notes, and snippets.

@poying
Last active June 13, 2016 03:40
Show Gist options
  • Save poying/45e6b176017d3a797109289750041513 to your computer and use it in GitHub Desktop.
Save poying/45e6b176017d3a797109289750041513 to your computer and use it in GitHub Desktop.

Electron、Elm 搭配使用

Electron 的 Browser 端

const callbacks = {};
let callbackId = 0;

glbale.electron = window.electron = function (event, args, cb) {
  // 產生 id 是為了讓之後 done 事件被觸發時能夠找到對應的 callback function
  const id = callbackId++;
  
  // timeout 機制
  const timeout = setTimeout(() => {
    delete callbacks[id];
    cb(new Error('Timeout'));
  }, 5000);
  
  callbacks[id] = (err, args) => {
    clearTimeout(timeout);
    delete callbacks[id];
    cb(err, args);
  };
  
  ipcRenderer.send(event, id, args);
};

ipcRenderer.on('done', (event, id, err, args) => {
  const cb = callbacks[id];
  if (cb) {
    cb(err, args);
  }
});

Electron 的 Node 端

// window.js
const {ipcMain} = require('electron');

module.exports = win => {
  ipcMain.on('window.resize', (event, id, [w, h]) => {
    win.setSize(w, h);
    event.sender.send('electron.done', id, null, []);
  });
};

Elm JavaScript 部分

// Native/Electron/Window.js
var _user$repo$Native_Electron_Window = function () {
  function resize(size) {
    // 建立 Task
    return _elm_lang$core$Native_Scheduler.nativeBinding(cb => {
      electron('window.resize', [size._0, size._1], err => {
        if (err) {
          cb(_elm_lang$core$Native_Scheduler.fail({ ctor: 'ElectronError', _0: err.message }));
        } else {
          cb(_elm_lang$core$Native_Scheduler.succeed({ ctor: '_Tuple0' }));
        }
      });
    });
  }
  
  return {
    resize
  };
}();

Elm

import Native.Electron.Window

type ElectronError = ElectronError String

resize : (Int, Int) -> Task ElectronError ()
resize = Native.Electron.Window.resize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment