您听说过观察者模式吗?如果没有,link here 或者只是在 js 设计模式书中搜索它。观察者模式的特点是它在这些情况下非常有用且模块化(且高效),其中一个对象监听另一个对象的变化。
正如我在您的问题中看到的,不一定需要观察者模式,因为仅当单击或选择 一个 对象时才会显示对象。但是,如果您只有选择两个单选按钮,那么只有在两个中显示,那么你真的需要它。
因为你说你想要一个干净/灵活的解决方案,你需要一个设计模式的答案;)这是我的尝试:
(skip the code and see the codepen i made for you)
HTML:
<!--
1.what is data-publish?
if data-publish gets clicked or changed(depends wheter is input or select option), it notifies every element in DOM with data-observe with the same value as our clicked data-publish.
2.what is data-observe?
data-observe="4 5" observes the DOM elements with data-publish="4" & data-publish="5" for a change. data-observe="4 5" gets display:block only when data-publish="4" & data-publish="5" are selected(it can be the case where data-publish="4 5", and it works the same)
3. what is data-name?
data-name is a unique name of a DOM element which as data-observe attribute. this is set at page load, js insert in DOM a random string to data-name
-->
<p>combinations:(note, at page load, nothing is selected)</p>
<p>1 & 1</p>
<p>2 & 2</p>
<p>1 & 1 -> & 7 </p>
<p>1 & 1 & 10 & 10 -> & 7</p>
<select>
<option selected></option>
<option data-publish="1">pub 1</option>
<option data-publish="2">pub 2</option>
<option data-publish="3">pub 3</option>
</select>
<select>
<option selected></option>
<option data-publish="4">pub 4</option>
<option data-publish="1">pub 1</option>
<option data-publish="5">pub 5</option>
</select>
<select>
<option selected></option>
<option data-publish="10">pub 10</option>
<option data-publish="11">pub 11</option>
<option data-publish="12">pub 12</option>
</select>
<select>
<option selected></option>
<option data-publish="10 2">pub 10 & 2</option>
<option data-publish="13">pub 13</option>
<option data-publish="14">pub 14</option>
</select>
<p data-observe="1">(triggered by two 1)
pub 7<input type="checkbox" data-publish="7">
pub 8<input type="checkbox" data-publish="8">
pub 9<input type="checkbox" data-publish="9">
</p>
<p data-observe="2">triggered by two 2</p>
<p data-observe="1 7">i am triggered by two 1, one 7</p>
<p data-observe="1 7 10">i am triggered by two 1, one 7, two 10</p>
CSS:
[data-observe] {
display: none;
}
Javascript:
/*
* @author: Ali Cerrahoglu
* @thing: awesome thing
* @use: no defaults...so version 1.0.0
it's a simple pub-sub which shows divs based on select options and radio/checkbox inputs
*/
// revealing module pattern
var ObserverPlugin = (function(){
// here will be stored every DOM object which has
// data-observe attr and data-name attr (data-name will be served
// as a key , which will store another object with a reference to the DOM object
// how many object does it observe)
var observers = {};
var publishers = [];
// observer pattern & revealing module pattern
var observer = (function(){
var topics = {};
var publish = function(topic, reference) {
// if there is no topic on the publish call, well get out !
if (!topics[topic]) {
return false;
}
// self invoked funciton, which calls the function passed when
// the topic was subscribed (if more then one function was published on the same topic
// then call each one of them)
(function(){
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, reference);
}
})();
};
var subscribe = function(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
topics[topic].push({
func: func
});
};
return {
subscribe: subscribe,
publish: publish,
topics: topics
}
})();
// creates random string, used to make data-name random for observers
var _makeRandomString = function() {
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
// verifies if eleme existis in array, if not, returns false
var _isInside = function( elem, array ) {
return array.indexOf(elem) > -1;
}
// topic is the topic
// reference is a reference to the DOM object clicked
var _observerFunction = function(topic, reference) {
var number = reference.attr('data-value');
var topics = topic.toString().split(' ');
var length = topics.length;
for( var key in observers ) {
for( var i = 0; i < length; i +=1 ) {
if( _isInside( topics[i], observers[key].topicsObserved ) ) {
// it exists
observers[key].sum += Number(number);
// 'number' is a string, so we have to convert it back to number
}
}
if( observers[key].sum == 0 ) {
// it is 0, so show that goddam DOM obj ! :))
// again, put here 'var' for clarity
// does not affect the code
var display = 'block';
}
else {
// it is not 0, so hide it
var display = 'none';
}
observers[key].reference.css('display', display);
}
// change value to -1 or 1
if( number == '-1' ) {
reference.attr('data-value', '1');
}
else {
reference.attr('data-value', '-1');
}
}
/*
* lets say we have 3 DOM objects with data-publish="1"
and 2 DOM objects with data-publish="2"
and one with data-observe="1 2";
so data-observe has to be called 5 times in order for him to be shown on the page;
each DOM object with data-publish will be added at runtime a data-value attribute
which will be -1 or 1. each time it is clicked or changed, it changes to the opposite.
this serves as data-observes will have a property named sum, which will be in the previous case 5
5 gets calculated with -1, or 1 when clicked data-publish DOM object.
So if i click first at data-publish="1" , 5 becomes 4. if i click again the same data-publish, becomes 5.
when sum property becomes 0, the data-observe is shown.
this function calculates how many data-publish="1" exists and so on
(it also does the other stuff needed for publishers)
*/
var _managePublishers = function() {
$('[data-publish]').each(function(){
var el = $(this);
// adds that value data, remember it? :D
el.attr('data-value', '-1');
// trim in case data-publish = "1 2 3" and store in an array
var publisher = el.data('publish').toString();
// we subscripe 'publisher' topic, but we check each string in topic
// here is tricky. if one publishers has more than one topic inside data-publish
// then we subscribe topic, but we check for topic's substring in publishers
var topics = publisher.split(' ');
if( !observer.topics[publisher] ) {
// we subscribe data-publish topic, becouse when we click it we want to fire something, no?
observer.subscribe( publisher, _observerFunction );
}
// but here in publishers we add only the substrings
for( var key in topics ) {
if( publishers[topics[key]] ) {
// the publisher exists
publishers[topics[key]] += 1;
}
else {
// the publisher doesn't exist
publishers[topics[key]] = 1;
}
}
});
}
// gets the observers, calculates sum, caches their reference
var _manageObservers = function() {
$('[data-observe]').each(function(){
var el = $(this);
// create random data-name
el.attr('data-name', _makeRandomString());
var datas = el.data('observe').toString().split(' '); // make an array again if we have multiple attachments
observers[el.data('name')] = (function(){
var sum = (function(){
var sum2 = 0;
// if datas[key] is found in publishers array, add it to sum
for( var key in datas ) {
var temp = publishers[datas[key]];
if( temp ) {
sum2 += temp;
}
}
return sum2;
})();
var reference = el; // caching, so it is faster !
var topicsObserved = datas;
// we need this when a user clicks data-publish, we need to see which DOM obj. are observing this.
// i really like revealing module pattern...i got used to it
return {
sum: sum,
reference: reference,
topicsObserved: topicsObserved
}
})();
})
}
var init = function() {
_managePublishers();
_manageObservers();
$('[data-publish]').on( 'click', function(){
observer.publish( $(this).data('publish'), $(this) );
});
$('select').on('change', function(){
var cache = $(this);
// if in this select there is an option which has value 1(there is chance that it triggered a succesfull publish) we publish that too
observer.publish( cache.find('[data-value="1"]').data('publish'), cache.find('[data-value="1"]') );
var el = cache.find('[data-publish]:selected');
observer.publish( el.data('publish'), el );
})
}
return {
init: init,
// in case you want to add after page load
// warning: i didn't test these methods. maybe it can be a bug somewhere
// it is not in my scope to test these, as i won't need for this example any adding after page load
publish: observer.publish,
subscribe: observer.subscribe
}
})();
ObserverPlugin.init();
是的,就是这样。你可以再次看到我的 codepen (here)
我以插件的形式制作了它。您可以将多个发布者附加到观察者,可以将具有相同值的多个发布者附加到一个观察者,或者您可以仅将一个发布者附加到一个观察者。我试图让它尽可能高效。我希望这可以帮助你 Jashwant :)
(已编辑。现在它支持数据发布中的多个字符串,玩得开心!)
(已编辑。您不必向 HTML 观察者添加随机数据名称字符串)