我正在尝试使用以下代码在 jQuery 中实现 Pub/Sub 模式:
$.each({
trigger : 'publish',
on : 'subscribe',
off : 'unsubscribe'
}, function ( key, val) {
jQuery[val] = function() {
o[key].apply( o, arguments );
};
});
这工作正常,直到我尝试构建具有多个实例的东西。
我有一个应用于每个 $('.activity_radio')
的事件对象div 元素。当我单击任何 $('.activity_radio')
内的单选按钮时div $.subscribe
事件将根据 activity_radio
的数量触发 (X) 次div 位于页面上。
如何发布/订阅仅基于特定 div 的事件?
代码
radio 事件(radio-activity.js)
var activity = {
init : function ( element ) {
// get our boilerplate code
this.activity = new util.factories.activity();
this.element = element;
this.$element = $(element);
// other init code
// gather our radio elements
this.target_element = this.$elem.find('input[type=radio]');
// send our radio elements to onSelect
this.activity.onSelect(this.target_element);
// trigger click function that will subscribe us to onSelect publish events
this.click()
},
// subscribe to events
click : function()
{
$.subscribe('activity.input.select', function ( event, data ){
// we have access to the value the user has clicked
console.log(data);
// trigger another function // do something else
});
}
}
基本事件样板代码(activity-factory.js)
var activity_factory = factory.extend({
init: function(e)
{
// init code
},
onSelect : function ( inputs ) {
inputs.on('click', function(){
// do some processing
// retrieve the value
var data = $(this).val();
// announce that the event has occured;
$.publish( 'activity.input.select', data );
});
}
}
});
DOM 就绪时触发
$(function(){
// foreach DOM element with the class of activity_radio
$('.activity_radio').each(function(){
// trigger the init func in activity object
activity.init(this);
});
});
最佳答案
您可以将订阅/发布编写为插件
$.each({
trigger : 'publish',
on : 'subscribe',
off : 'unsubscribe'
}, function ( key, val) {
jQuery.fn[val] = function() {
this[key].apply(this, Array.prototype.slice.call(arguments));
};
});
您将能够在 $element 上调用它
this.$element.subscribe('activity.input.select', function(event, data) {
和
onSelect: function ( inputs ) {
var self = this;
inputs.on('click', function(){
// do some processing
// retrieve the value
var data = $(this).val();
// announce that the event has occured;
self.$element.publish('activity.input.select', data);
});
}
关于javascript - jQuery 中的 Pub/Sub 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18140760/