如何拥有一个对象的原型自动执行功能来自动运行JavaScript中所有的孩子? [英] How to have self-executing function in an object's prototype be auto-run for all children in JavaScript?

查看:103
本文介绍了如何拥有一个对象的原型自动执行功能来自动运行JavaScript中所有的孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

父对象的每个'孩子'必须订阅事件聚合一个固定的活动:例如:

Every 'child' of a parent object needs to be subscribed to a fixed event in the event aggregator: For example:

var dispatcher = EventAggregator.create();

有在应用程序的多个若干意见,所有意见必须订阅关闭事件。使用主要成分:

There are multiple 'views' in the application and all views must be subscribed to the close event. Using Backbone:

Backbone.View.prototype.close = function(){
  //close logic
};

现在每一个视图需要订阅的事件聚合,即 VAR调度关闭事件,而无需显式调用做到这一点的方法。那是不是说不停:

Now every view needs to subscribe to the "close" event on the event aggregator i.e. var dispatcher without needing to explicitly call a method to do it. That is instead of constantly saying:

dispatcher.on('关闭',this.close) ParentView.prototype.someMethod.apply()

在每一个观点,即是Backbone.View的一个实例是有办法有自动订阅了调度?

in every view that is an instance of Backbone.View is there a way to have all views automatically be subscribed to the close event on the dispatcher?

能像这样工作:(似乎并不在我的情况,因为这个被绑定到窗口:)

Could something like this work: (doesn't seem to in my case since this gets bound to window :)

Backbone.View.prototype.subscribeClose: (function(){
 dispatcher.on('close',this.close);
})();

因为这本失败势必窗口。这将是一个更好的方式来退出这个功能还是我不得不手动调用父/原型方法,以确保订阅总是会发生?是否有另一种方式JS说我可能不知道呢?

This fails since this is bound to window. What would be a better way to pull this off or do I have to manually call a parent/prototype method to ensure that subscription always happens? Is there 'another' way in JS that I'm probably not aware of?

更新:添加小提琴双方的意见应触发在玉兰油,但只有一个视图,其中 subscribeOnClose 添加到原型似乎是工作的罚款(试行按丹的答案)。这两种观点的以触发虽然作出回应。只需用仿真模型触发器现在。

UPDATE: Adding a fiddle Both the views should trigger on 'olay' but only one view in which the subscribeOnClose is added to the prototype seems to be working fine (experimented as per Dan's answer). Both views do not respond to the trigger though. Just simulating the trigger with a model for now.

推荐答案

我不想把这个,除非真的有必要,但如果你真的希望这适用的所有的视图实例,而不需要让他们从自己的自定义基本视图类下降,你可以尝试这样的事情(覆盖 Backbone.View ,内置的基本视图类的构造函数):

Update

I didn't want to bring this out unless really necessary, but if you really want this to apply to all view instances, without the need to have them descend from your own custom base view class, you can try something like this (overriding Backbone.View, the built-in base view class constructor):

http://jsfiddle.net/D9gR7/5/

$( document ).ready( function () {

  // Create your actual object here

  var dispatcher = _.clone( Backbone.Events );

  ( function () {

    var ctor = Backbone.View;

    Backbone.View = Backbone.View.extend( {

      constructor : function ( options ) {

        ctor.apply( this, arguments );

        dispatcher.on( 'close', this.close, this );

      },
      // constructor


      close : function () {

          console.log( this.cid );

      }
      // close

    } );

    Backbone.View.prototype.constructor = Backbone.View;

  } )();


  var View = Backbone.View.extend( {} );


  var views = [];

  var i;

  for ( i = 0 ; i < 10 ; ++i ) {

    views.push( new Backbone.View );

  }


  for ( i = 0 ; i < 10 ; ++i ) {

    views.push( new View );

  }

  dispatcher.trigger( 'close' );

} );

原来的答案

有您的code一堆问题。什么是这样的(参见控制台输出,很明显)?我认为这是pretty你要多少东西。你只需要确保你调用父初始化()当你重写子类中的方法。另外,如果你想在某个时候完全吹走的观点的情况下,确保你调用 dispatcher.off(NULL,NULL,view_instance)

Original Answer

There are a bunch of issues with your code. What about something like this (see the console for output, obviously)? I think this is pretty much what you're going for. You'd just need to make sure you call the parent initialize() when you override the method in sub classes. Also, if you want to completely blow away the view instances at some point, make sure you call dispatcher.off( null, null, view_instance ).

http://jsfiddle.net/D9gR7/

$( document ).ready( function () {

  // Create your actual object here

  var dispatcher = _.clone( Backbone.Events );

  var View = Backbone.View.extend( {

    initialize : function ( options ) {

      dispatcher.on( 'close', this.close, this );

    },


    close : function () {

      console.log( this.el.id );

    }

  } );


  var Some_Kind_Of_View = View.extend( {

    initialize : function ( options ) {

      View.prototype.initialize.apply( this, arguments );

      // ...

    }

  } );


  var view1 = new View( {

    el : $( "#MyDiv" )[0],

  } );


  var view2 = new Some_Kind_Of_View( {

    el : $( "#MyDiv2" )[0]

  } );


  dispatcher.trigger( 'close' );

} );

你的榜样code的一些问题:

Some issues with your example code:

var V1 = Backbone.View.extend({

    // JMM: If you pass `el` to `extend()`, any instances you create
    // from the class will be tied to the same DOM element, unless
    // you pass a different `el` to the view constructors. Maybe
    // that's what you want.

    el: '#MyDiv',

    initialize: function() {
        var self = this;

        // JMM: You're assigning `undefined` to this prototype
        // property. And you're trying to register the
        // return value of self.alert() (`undefined`) as
        // the handler for the `olay` event.

        Backbone.View.prototype.subOnClose = (function(){
            model.on('olay',self.alert('olay'));
        })();
    },

    alert: function(s) {
        alert('V1 -->' + s);
    }
});

这篇关于如何拥有一个对象的原型自动执行功能来自动运行JavaScript中所有的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆