0

我正在尝试使用以下代码在 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事件将根据页面上 div 的数量触发 (X) 次activity_radio

如何仅基于特定 div 发布/订阅事件?

代码

无线电活动 ( 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);
       });
       
    
   });
4

1 回答 1

2

您可以将订阅/发布编写为插件

$.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);


    });
}
于 2013-08-09T08:41:18.003 回答