我正在学习发布者/订阅者模式,并做了一个简单的例子来更好地理解它。
var Publisher = {
subscribers: {},
Subscribe: function (event, callback) {
if (Publisher[event] && typeof callback === "function") {
if (Publisher.subscribers[event]) {
Publisher.subscribers[event].callbacks.push(callback);
}
else {
Publisher.subscribers[event] = { callbacks: [callback] };
}
}
},
Publish: function (event) {
if (Publisher.subscribers[event].callbacks) {
for (callback in Publisher.subscribers[event].callbacks) {
Publisher.subscribers[event].callbacks[callback].apply(null);
}
}
},
PublishOnClick: function (event, argument) {
Publisher.Publish(event, argument);
}
};
var Subscriber1 = {
initialize: function () {
if (Publisher.Subscribe) {
Publisher.Subscribe("PublishOnClick", Subscriber1.Action);
}
},
Action: function (c) {
document.getElementById('result').innerHTML += "Button Clicked and the count is: " + c;
c++;
}
};
Subscriber1.initialize();
var c = 1;
var fld2 = document.getElementById("myfield2");
if (fld2.addEventListener) {
fld2.addEventListener("click", function() { Publisher.PublishOnClick("PublishOnClick", [c]); }, false);
} else if (fld2.attachEvent) {
fld2.attachEvent("onclick", function() { Publisher.PublishOnClick("PublishOnClick", [c]); });
}
我有一个按钮和部分视图,我试图通过按钮引发一个事件并在部分视图上显示计数。我得到了事件的提升并显示在部分视图上,但唯一的问题是计数