gpt4 book ai didi

javascript - 如何在 javascript 中创建自定义事件而不使用 DOM

转载 作者:行者123 更新时间:2023-12-03 06:13:40 24 4
gpt4 key购买 nike

我有两个对象。 ObjecA 触发事件 E,而 ObjectB 必须监听由 ObjectA (E) 触发的事件。ObjectA 仅当其中的属性在运行时更改时才发送。

提前致谢。

最佳答案

您可以使用 pubsub 模式

var pubsub = {};

(function(myObject) {

// Storage for topics that can be broadcast
// or listened to
var topics = {};

// An topic identifier
var subUid = -1;

// Publish or broadcast events of interest
// with a specific topic name and arguments
// such as the data to pass along
myObject.publish = function(topic, args) {

if (!topics[topic]) {
return false;
}

var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;

while (len--) {
subscribers[len].func(topic, args);
}

return this;
};

// Subscribe to events of interest
// with a specific topic name and a
// callback function, to be executed
// when the topic/event is observed
myObject.subscribe = function(topic, func) {

if (!topics[topic]) {
topics[topic] = [];
}

var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};

// Unsubscribe from a specific
// topic, based on a tokenized reference
// to the subscription
myObject.unsubscribe = function(token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return this;
};
}(pubsub));



Implementation:
// Another simple message handler

// A simple message logger that logs any topics and data received through our
// subscriber
var messageLogger = function(topics, data) {
console.log("Logging: " + topics + ": " + data);
};

// Subscribers listen for topics they have subscribed to and
// invoke a callback function (e.g messageLogger) once a new
// notification is broadcast on that topic
var subscription = pubsub.subscribe("inbox/newMessage", messageLogger);

// Publishers are in charge of publishing topics or notifications of
// interest to the application. e.g:

pubsub.publish("inbox/newMessage", "hello world!");

// or
pubsub.publish("inbox/newMessage", ["test", "a", "b", "c"]);

// or
pubsub.publish("inbox/newMessage", {
sender: "hello@google.com",
body: "Hey again!"
});

// We can also unsubscribe if we no longer wish for our subscribers
// to be notified
pubsub.unsubscribe(subscription);

// Once unsubscribed, this for example won't result in our
// messageLogger being executed as the subscriber is`enter code here`
// no longer listening
pubsub.publish("inbox/newMessage", "Hello! are you still there?");

关于javascript - 如何在 javascript 中创建自定义事件而不使用 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com