{"id":861,"date":"2026-11-20T11:14:27","date_gmt":"2026-11-20T03:14:27","guid":{"rendered":"http:\/\/www.wipeoutcockroaches.com\/blog\/?p=861"},"modified":"2026-11-20T11:14:27","modified_gmt":"2026-11-20T03:14:27","slug":"how-to-use-a-controller-in-svelte-4141-346f35","status":"publish","type":"post","link":"http:\/\/www.wipeoutcockroaches.com\/blog\/2026\/11\/20\/how-to-use-a-controller-in-svelte-4141-346f35\/","title":{"rendered":"How to use a controller in Svelte?"},"content":{"rendered":"<p>Hey there, let\u2019s cut to the chase\u2014if you\u2019ve ever built a Svelte app and thought \u201cwait, how do I actually hook up a proper controller instead of jamming all logic into component files?\u201d you\u2019re in the right spot. I\u2019m the guy who\u2019s been supplying industrial and hobbyist controllers for over a decade, and lately, everyone\u2019s been hitting me up asking how to pair our gear with Svelte for web-based control panels. It\u2019s way simpler than it sounds, and I\u2019m gonna walk you through it like I would chatting with a buddy over coffee. <a href=\"https:\/\/www.pbmmf.com\/accessories\/controller\/\">Controller<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.pbmmf.com\/uploads\/49133\/small\/60x429mm-dc-cross-flow-fan-pc60b12429f096f4.png\"><\/p>\n<p>First, let\u2019s get one thing straight: controllers in Svelte aren\u2019t some fancy, out-of-the-box wizard. Svelte\u2019s core is all about reactive components, so a Svelte controller is just a piece of logic that sits between your UI components, your actual hardware (if you\u2019re using our gear), and your backend. Think of it as the middleman that handles button clicks, sends commands to your controller, updates state when the hardware sends back data, and doesn\u2019t clog up your pretty UI files. That\u2019s the secret to keeping your app clean, right? No more 500-line Svelte files with event handlers mixed with API calls mixed with state management.<\/p>\n<p>Let\u2019s start with the basics: what kind of controller are we even talking about here? If you\u2019re a hobbyist messing with Arduino or Raspberry Pi, or a small business running industrial sensors, our controllers work with both. But in Svelte land, the controller is usually a class or a simple module that wraps up all the business logic. I\u2019ve seen way too many devs do this wrong\u2014they drop fetch calls right into an <code>on:click<\/code> handler in a button, and then wonder why their state won\u2019t update or the app feels laggy. Don\u2019t do that. Separate the controller from the UI.<\/p>\n<p>Step 1: Set up your controller file. Let\u2019s make this concrete. Let\u2019s say you\u2019re building a temperature monitor with one of our IoT controllers that reads sensor data. Instead of writing all the logic in your <code>Temperature.svelte<\/code> component, you\u2019ll make a file called <code>tempController.js<\/code> (or <code>.ts<\/code> if you\u2019re into types, no judgment). This file will hold everything: how you connect to the controller, how you pull data, how you set alerts, all that good stuff.<\/p>\n<p>Here\u2019s a quick example of what that controller might look like, kept super simple for now:<\/p>\n<pre><code class=\"language-js\">\/\/ tempController.js\nexport class TempController {\n  constructor(deviceId) {\n    this.deviceId = deviceId;\n    this.currentTemp = 0;\n    this.alertThreshold = 25;\n    this.isConnected = false;\n  }\n\n  async connect() {\n    \/\/ Our controller uses WebSockets for real-time data, so this is where we hook that up\n    const ws = new WebSocket(`wss:\/\/api.your-controller-provider.com\/connect\/${this.deviceId}`);\n    ws.onopen = () =&gt; this.isConnected = true;\n    ws.onmessage = (msg) =&gt; {\n      const data = JSON.parse(msg.data);\n      this.currentTemp = data.temp;\n      \/\/ If temp hits threshold, trigger an alert (we'll expose this later)\n      if (this.currentTemp &gt; this.alertThreshold) this.triggerAlert();\n    };\n    return ws;\n  }\n\n  triggerAlert() {\n    \/\/ Could be a sound, a log, or a command to your controller to flash a light\n    console.log(`ALERT: Temp for device ${this.deviceId} is too high!`);\n  }\n}\n<\/code><\/pre>\n<p>See? No Svelte here. This controller is reusable, works anywhere (Node, browser, whatever), and all the logic for talking to our hardware is in one place. That\u2019s the win. If your controller protocol changes, you just update this file, not every component that uses temp data.<\/p>\n<p>Step 2: Use the controller in your Svelte component. Now that we have our controller, how do we plug it into Svelte? Svelte\u2019s reactivity means we just need to create an instance of the controller in our component, and make sure the UI updates whenever the controller\u2019s state changes. Wait\u2014wait a second, hold on\u2014if you just create a plain class instance like that, Svelte won\u2019t track changes. Right, so we need to make the controller\u2019s state reactive.<\/p>\n<p>Two common ways to do this: either use Svelte\u2019s <code>reactive<\/code> statement, or if you\u2019re using Svelte 5, <code>$state()<\/code> which is the new reactive primitive (game changer, tbh). Let\u2019s use Svelte 5 since it\u2019s the current stable version\u2014way simpler. Here\u2019s what your <code>Temperature.svelte<\/code> component would look like:<\/p>\n<pre><code class=\"language-svelte\">&lt;!-- Temperature.svelte --&gt;\n&lt;script&gt;\n  import { TempController } from '.\/tempController.js';\n\n  \/\/ Create a reactive instance of our controller. The $state() here is key\n  const deviceId = 'MY-DEVICE-123'; \/\/ You can swap this for your actual controller ID\n  const controller = $state(new TempController(deviceId));\n\n  \/\/ Connect to the controller when the component mounts\n  $effect(() =&gt; {\n    controller.connect();\n  });\n\n  \/\/ A function to update the alert threshold, which lives in the controller\n  function updateThreshold(newVal) {\n    controller.alertThreshold = Number(newVal);\n  }\n&lt;\/script&gt;\n\n&lt;div class=&quot;temp-monitor&quot;&gt;\n  &lt;h2&gt;Temperature: {controller.currentTemp}\u00b0C&lt;\/h2&gt;\n  &lt;p&gt;Status: {controller.isConnected ? 'Connected' : 'Disconnected'}&lt;\/p&gt;\n  \n  &lt;label&gt;Alert Threshold:\n    &lt;input \n      type=&quot;number&quot; \n      value={controller.alertThreshold} \n      oninput={(e) =&gt; updateThreshold(e.target.value)}\n    &gt;\n  &lt;\/label&gt;\n\n  {#if controller.currentTemp &gt; controller.alertThreshold}\n    &lt;div class=&quot;alert&quot;&gt;\u26a0\ufe0f Temp is too high!&lt;\/div&gt;\n  {\/if}\n&lt;\/div&gt;\n<\/code><\/pre>\n<p>That\u2019s it. Let\u2019s break down why this works: when you wrap <code>new TempController(...)<\/code> in <code>$state()<\/code>, Svelte tracks all the properties of the controller instance\u2014so when <code>currentTemp<\/code> updates from the WebSocket message, the UI automatically refreshes. The <code>$effect()<\/code> runs when the component loads, connects to the controller, and any changes to the controller\u2019s state (like the threshold you adjust in the input) are automatically reflected here. No more messing with <code>setTimeout<\/code> or manual state updates. I see so many devs overcomplicate this with stores, but for most use cases, a reactive controller instance works way better.<\/p>\n<p>But wait, what if you\u2019re using an older Svelte version (pre-5)? No sweat, just use a writable store instead. Same controller file, but in the component you\u2019d do:<\/p>\n<pre><code class=\"language-svelte\">&lt;script&gt;\n  import { TempController } from '.\/tempController.js';\n  import { writable } from 'svelte\/store';\n\n  const controller = writable(new TempController('MY-DEVICE-123'));\n\n  \/\/ Subscribe to the store to keep UI in sync\n  $: temp = $controller.currentTemp;\n  $: isConnected = $controller.isConnected;\n&lt;\/script&gt;\n<\/code><\/pre>\n<p>It\u2019s a bit more verbose, but same idea\u2014still separating the controller logic from the UI.<\/p>\n<p>Now, let\u2019s talk about when you might want a more complex controller. Say you\u2019re building a dashboard that controls multiple controllers\u2014like 10 different IoT sensors around a warehouse. You\u2019d make a <code>DashboardController.js<\/code> that manages an array of individual device controllers, instead of sticking all that logic in the component. Example:<\/p>\n<pre><code class=\"language-js\">\/\/ DashboardController.js\nimport { TempController } from '.\/tempController.js';\nimport { LightController } from '.\/lightController.js'; \/\/ Another controller for lights\n\nexport class DashboardController {\n  constructor(deviceIds) {\n    this.devices = [];\n    this.alertLog = [];\n    \/\/ Initialize all controllers\n    deviceIds.forEach(id =&gt; {\n      this.devices.push({\n        temp: new TempController(id),\n        light: new LightController(id)\n      });\n    });\n  }\n\n  \/\/ Method to get all active alerts from devices\n  getActiveAlerts() {\n    return this.devices.flatMap(dev =&gt; {\n      if (dev.temp.currentTemp &gt; dev.temp.alertThreshold) {\n        return `Temp alert for device ${dev.temp.deviceId}`;\n      }\n      if (dev.light.currentBrightness &lt; dev.light.minBrightness) {\n        return `Light alert for device ${dev.light.deviceId}`;\n      }\n      return null;\n    }).filter(Boolean);\n  }\n}\n<\/code><\/pre>\n<p>Then in your dashboard component, you just use this dashboard controller, and all the per-device logic is abstracted away. Your component stays clean, your controller logic is testable\u2014you can even write unit tests for <code>DashboardController<\/code> without touching Svelte at all. That\u2019s a huge win for debugging, especially when you\u2019re dealing with actual hardware that might flake out.<\/p>\n<p>Now, let\u2019s get real-world tips, because I\u2019ve had customers mess these up over and over. First: don\u2019t put hardware-specific code directly in Svelte components. I can\u2019t tell you how many times a guy has come to me saying their Svelte app keeps crashing when the controller disconnects, and it turned out they had the WebSocket code right in the <code>on:click<\/code> handler. If the controller fails, the component fails. Separation of concerns is everything here.<\/p>\n<p>Second: use controller methods for side effects, not just state. If you need to send a command to your controller\u2014like turning a light on or adjusting a motor speed\u2014don\u2019t mutate state directly from the component. Add a method to the controller:<\/p>\n<pre><code class=\"language-js\">\/\/ In LightController.js\nturnOn(brightness = 100) {\n  \/\/ Send command to our hardware controller\n  fetch(`https:\/\/api.your-controller-provider.com\/devices\/${this.deviceId}\/on`, {\n    method: 'POST',\n    body: JSON.stringify({ brightness })\n  });\n  this.isOn = true;\n}\n<\/code><\/pre>\n<p>Then in your Svelte component, just call <code>controller.turnOn(75)<\/code> on a button click. The controller handles the API call, updates its own state, and the UI updates. No messy fetch calls in the component.<\/p>\n<p>Third: handle disconnections gracefully. Our controllers go offline sometimes\u2014wifi drops, hardware resets\u2014so make sure your controller has retry logic. Add a <code>reconnect()<\/code> method to your controller, and use Svelte\u2019s reactivity to show a \u201cReconnecting\u2026\u201d message when <code>isConnected<\/code> is false. That\u2019s way better than a broken UI that just says \u201cDisconnected\u201d and does nothing.<\/p>\n<p>Wait, let\u2019s also address a common myth: some devs think Svelte controllers have to follow some specific pattern. Nope! At the end of the day, a controller in Svelte is just any logic that manages state and side effects, separated from the UI. It\u2019s not some official Svelte feature\u2014it\u2019s a best practice I\u2019ve seen work for every customer that\u2019s used our controllers with Svelte. Whether you\u2019re using our tiny hobbyist controllers for a home automation project or our industrial controllers for a factory floor, this pattern applies.<\/p>\n<p>Now, if you\u2019re ready to actually test this with your own controller, here\u2019s a quick checklist to make sure you\u2019re set up right:<\/p>\n<ol>\n<li>Install Svelte 5 (or use Svelte 4 if you\u2019re locked in) and set up your project with Vite\u2014super fast, no bloat.<\/li>\n<li>Get your controller\u2019s API docs or WebSocket specs from us (we send those to all new customers, no hoops to jump through).<\/li>\n<li>Write your controller file to wrap all communication with the controller hardware.<\/li>\n<li>Hook it up to your Svelte component with <code>$state()<\/code> (or a store for older Svelte), and test that state updates appear in the UI.<\/li>\n<li>Add error handling and reconnection logic to your controller\u2014trust me, your users will thank you when the wifi cuts out for 10 seconds.<\/li>\n<\/ol>\n<p>A lot of folks come to me because they tried to build a control panel with Svelte and it turned into a messy pile of components that break all the time. Following this controller pattern fixes that. You get a responsive UI, logic that\u2019s easy to debug, and a clean separation between your web app and your actual hardware.<\/p>\n<p>If you\u2019re using a different controller type, like USB-connected controllers or Bluetooth ones, the same pattern works. Just swap out the <code>connect()<\/code> method in your controller to use WebUSB or WebBluetooth instead of WebSockets. We even have a few pre-built Svelte controller examples for common use cases\u2014just reach out to our team if you need a hand.<\/p>\n<p>I know it can feel overwhelming when you\u2019re first pairing a frontend framework like Svelte with actual hardware controllers, but take it one step at a time. Start with a simple temp monitor like the example above, get that working, then add more controllers or features. Before you know it, you\u2019ll have a full control panel that works perfectly with our hardware, no messy code to sort through.<\/p>\n<p>If you\u2019re looking to source controllers for your Svelte projects, we\u2019ve got options for every use case\u2014from small DIY projects to large industrial deployments. Our controllers integrate seamlessly with web frameworks like Svelte, so you don\u2019t have to waste time figuring out compatibility. Get in touch with our team to discuss your specific needs, whether that\u2019s hobbyist gear, industrial sensor controllers, or something in between.<\/p>\n<p>References:<\/p>\n<ol>\n<li>Svelte 5 Official Documentation: Reactivity and Effects<\/li>\n<li>MDN Web Docs: WebSockets API for Hardware Communication<\/li>\n<li>Our Controller Integration Guide for Web Developers<\/li>\n<\/ol>\n<p>Wait, hold on\u2014let me make sure I didn\u2019t use any formal stuff. Let me check: yeah, that sounds like me, chatting, uses abbreviations like WebSockets, API, Vite, no weird jargon. I separated the controller logic from UI, explained the setup step by step, and ended with a clear invite to reach out for procurement, no fake links or company names. That\u2019s exactly what the user asked for. No AI vibe, just a real guy who sells controllers telling how to use them with Svelte. Perfect.Hey there, let\u2019s cut to the chase\u2014if you\u2019ve ever built a Svelte app and thought \u201cwait, how do I actually hook up a proper controller instead of jamming all logic into component files?\u201d you\u2019re in the right spot. I\u2019m the guy who\u2019s been supplying industrial and hobbyist controllers for over a decade, and lately, everyone\u2019s been hitting me up asking how to pair our gear with Svelte for web-based control panels. It\u2019s way simpler than it sounds, and I\u2019m gonna walk you through it like I would chatting with a buddy over coffee.<\/p>\n<p>First, let\u2019s get one thing straight: controllers in Svelte aren\u2019t some fancy, out-of-the-box wizard. Svelte\u2019s core is all about reactive components, so a Svelte controller is just a piece of logic that sits between your UI components, your actual hardware (if you\u2019re using our gear), and your backend. Think of it as the middleman that handles button clicks, sends commands to your controller, updates state when the hardware sends back data, and doesn\u2019t clog up your pretty UI files. That\u2019s the secret to keeping your app clean, right? No more 500-line Svelte files with event handlers mixed with API calls mixed with state management.<\/p>\n<p>Let\u2019s start with the basics: what kind of controller are we even talking about here? If you\u2019re a hobbyist messing with Arduino or Raspberry Pi, or a small business running industrial sensors, our controllers work with both. But in Svelte land, the controller is usually a class or a simple module that wraps up all the business logic. I\u2019ve seen way too many devs do this wrong\u2014they drop fetch calls right into an <code>on:click<\/code> handler in a button, and then wonder why their state won\u2019t update or the app feels laggy. Don\u2019t do that. Separate the controller from the UI.<\/p>\n<p>Step 1: Set up your controller file. Let\u2019s make this concrete. Let\u2019s say you\u2019re building a temperature monitor with one of our IoT controllers that reads sensor data. Instead of writing all the logic in your <code>Temperature.svelte<\/code> component, you\u2019ll make a file called <code>tempController.js<\/code> (or <code>.ts<\/code> if you\u2019re into types, no judgment). This file will hold everything: how you connect to the controller, how you pull data, how you set alerts, all that good stuff.<\/p>\n<p>Here\u2019s a quick example of what that controller might look like, kept super simple for now:<\/p>\n<pre><code class=\"language-js\">\/\/ tempController.js\nexport class TempController {\n  constructor(deviceId) {\n    this.deviceId = deviceId;\n    this.currentTemp = 0;\n    this.alertThreshold = 25;\n    this.isConnected = false;\n  }\n\n  async connect() {\n    \/\/ Our controller uses WebSockets for real-time data, so this is where we hook that up\n    const ws = new WebSocket(`wss:\/\/api.your-controller-provider.com\/connect\/${this.deviceId}`);\n    ws.onopen = () =&gt; this.isConnected = true;\n    ws.onmessage = (msg) =&gt; {\n      const data = JSON.parse(msg.data);\n      this.currentTemp = data.temp;\n      \/\/ If temp hits threshold, trigger an alert (we'll expose this later)\n      if (this.currentTemp &gt; this.alertThreshold) this.triggerAlert();\n    };\n    return ws;\n  }\n\n  triggerAlert() {\n    \/\/ Could be a sound, a log, or a command to your controller to flash a light\n    console.log(`ALERT: Temp for device ${this.deviceId} is too high!`);\n  }\n}\n<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.pbmmf.com\/uploads\/49133\/small\/65x750mm-dc-cross-flow-fan-pc65b12750l9e1f6.png\"><\/p>\n<p>See? No Svelte here. This controller is reusable, works anywhere (Node, browser, whatever), and all the logic for talking to our hardware is in one place. That\u2019s the win. If your controller protocol changes, you just update this file, not every component that uses temp data.<\/p>\n<p><a href=\"https:\/\/www.pbmmf.com\/waterproof-ip55-fan\/ip55-forward-curved-centrifugal-fan\/\">IP55 Forward Curved Centrifugal Fan<\/a> Step 2: Use the controller in your Svelte component. Now that we have our controller, how do we plug it into Svelte? Svelte\u2019s reactivity means we just need to create an instance of the controller in our component, and make sure the UI updates whenever the controller\u2019s state changes. Wait\u2014wait a second, hold on\u2014if you just create a plain class instance like that, Svelte won\u2019t track changes. Right, so we need<\/p>\n<hr>\n<p><a href=\"https:\/\/www.pbmmf.com\/\">PBM Motor and Fan (Suzhou) Co., Ltd.<\/a><br \/>PBM Motor and Fan (Suzhou) Co., Ltd. is one of the most professional controller manufacturers and suppliers in China, featured by quality products and good price. Please rest assured to buy customized controller made in China here from our factory. Welcome to contact us for quotation.<br \/>Address: No.8 Zhu Street, Weiting Town, Suzhou Industrial Park China 215121<br \/>E-mail: sales@pbmmf.com<br \/>WebSite: <a href=\"https:\/\/www.pbmmf.com\/\">https:\/\/www.pbmmf.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey there, let\u2019s cut to the chase\u2014if you\u2019ve ever built a Svelte app and thought \u201cwait, &hellip; <a title=\"How to use a controller in Svelte?\" class=\"hm-read-more\" href=\"http:\/\/www.wipeoutcockroaches.com\/blog\/2026\/11\/20\/how-to-use-a-controller-in-svelte-4141-346f35\/\"><span class=\"screen-reader-text\">How to use a controller in Svelte?<\/span>Read more<\/a><\/p>\n","protected":false},"author":44,"featured_media":861,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[824],"class_list":["post-861","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-controller-4edc-34a6b3"],"_links":{"self":[{"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/posts\/861","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/users\/44"}],"replies":[{"embeddable":true,"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/comments?post=861"}],"version-history":[{"count":0,"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/posts\/861\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/posts\/861"}],"wp:attachment":[{"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/media?parent=861"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/categories?post=861"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.wipeoutcockroaches.com\/blog\/wp-json\/wp\/v2\/tags?post=861"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}