Skip to content

Commit

Permalink
Add app watcher on data change
Browse files Browse the repository at this point in the history
  • Loading branch information
javalikescript committed Jan 1, 2025
1 parent cb63435 commit aaa5ef2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
4 changes: 1 addition & 3 deletions extensions/web-base/web-base.lua
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,7 @@ local function webSocketBroadcast(data)
logger:fine('WebSocket broadcast')
local message = json.encode(data)
for _, websocket in ipairs(websockets) do
if not websocket.lhaEvent or websocket.lhaEvent == data.event then
websocket:sendTextMessage(message)
end
websocket:sendTextMessage(message)
end
end

Expand Down
41 changes: 40 additions & 1 deletion extensions/web-base/www/app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ var app = new Vue({
menu: '',
hideMenu: window.innerWidth < 360,
dialog: '',
watchers: [],
page: '',
path: '',
pages: {},
Expand Down Expand Up @@ -174,6 +175,25 @@ var app = new Vue({
this.toPage('home');
}
},
watchDataChange: function(path, fn) {
var parts = path.split('/', 2);
var thingId = parts[0];
var propName = parts[1];
var watcher = {thingId: thingId, propertyName: propName, fn: fn};
this.watchers.push(watcher);
return watcher;
},
unwatchDataChange: function(watcherOrFn) {
var i = 0;
while (i < this.watchers.length) {
var watcher = this.watchers[i];
if (watcher === watcherOrFn || watcher.fn === watcherOrFn) {
this.watchers.splice(i, 1);
} else {
i++;
}
}
},
onMessage: function(message) {
//console.log('onMessage', message);
if (typeof message !== 'object') {
Expand All @@ -192,8 +212,27 @@ var app = new Vue({
}
}
}
this.callPage(this.page, 'onDataChange', message.data);
}
this.watchers.forEach(function(watcher) {
var thingId = watcher.thingId;
if (thingId) {
var props = message.data[thingId];
if (props) {
var name = watcher.propertyName;
if (name) {
var value = props[name];
if (value !== undefined) {
watcher.fn(value);
}
} else {
watcher.fn(props);
}
}
} else {
watcher.fn(message.data);
}
});
this.callPage(this.page, 'onDataChange', message.data);
break;
case 'logs':
if (Array.isArray(message.logs)) {
Expand Down

0 comments on commit aaa5ef2

Please sign in to comment.