diff --git a/README.md b/README.md index 80f90a4e8564..2c98c4048709 100644 --- a/README.md +++ b/README.md @@ -172,8 +172,10 @@ the node will come online later. `query` must be a valid query, chosen from `BaseControl.Query`. A full list of currently supported queries was shown above. The `callback` function will get one argument: The new value of the noun that triggered the event. `listen` returns a unique id for the installed listener -that could later be used to cancel it. - +that could later be used to cancel it. `listen` also returns a boolean as the +second value: It indicates whether an attempt was made at installing the +listener. If the noun was not yet known (`false`), the listener is still kept +and will be installed as soon as the noun is registered. ```lua bc = require("bc"):finalize{"some_noun"} bc:listen("some_noun", bc.Query.Change, function(value) diff --git a/bc.lua b/bc.lua index 40d0fc82c385..f2ff898f4b4a 100644 --- a/bc.lua +++ b/bc.lua @@ -433,6 +433,14 @@ function BaseControl:_network_handler(remote, msg) elseif msg.ty == Message.Register then for _, noun in ipairs(msg.nouns or {}) do self.remote_nouns[noun] = remote + for id, l in pairs(self.listeners[noun] or {}) do + self.network:send(remote, { + ty=Message.ListenRequest, + noun=noun, + id=id, + query=l.query, + }) + end end for _, verb in ipairs(msg.verbs or {}) do self.remote_verbs[verb] = remote diff --git a/tests/listening.lua b/tests/listening.lua index dbe0948efaf0..d6a6e4024d9a 100644 --- a/tests/listening.lua +++ b/tests/listening.lua @@ -195,3 +195,22 @@ function test_listen_cancel_remote() bc1:set("lcanr1", 21) assert_equal(1, n, "wrong number of listener invokations") end + +function test_listen_late_install() + local bc1 = BaseControl:new() + local addr1 = network.get_scene() + + local n = 0 + bc1:listen("late1", BaseControl.Query.Change, function() + n = n + 1 + end) + + local bc2 = BaseControl:new() + local addr2 = network.get_scene() + bc2:register("late1", 1234) + bc2:finalize() + + assert_equal(0, n, "wrong number of listener invokations") + bc2:set("late1", 34) + assert_equal(1, n, "wrong number of listener invokations") +end