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 に答える