0

Is there a handy way to throw/catch (custom) events from/to multiple levels of child/parent views in Backbone?

Let me explain my situation. I'm catching "keydown" events and check if some interactions should been done on the parent level. If not, then I'm calling the childView function for that. My BaseView looks something like this:

var BaseView = Backbone.View.extend({

  keydown: function(e){
    return this;
  },

});

It works fine until I'm not trying to throw other customEvents to interact with childViews of childViews. Which by the way, don't know about the existence of themselves.

I can't just simple do something like the stuff below, cause my parent don't even know all childViews of the subView. I'm trying to do something like this:

eg. Blur the subChildViews input

Parent.subview.subsubview.trigger('blurInput');

I'm really sure I'm on the wrong way with my event-pushing-"keydown"-method, could someone point me the right direction?

EDIT:

The raw BackboneJS isn't really build for something like that, but there is a Module out there. MarionetteJS was my solution, it provides everything I was looking for. Subviews, modular logic and an optimized cross view event system.

There is an awesome getting started tutorial on smashingmagazine.com

4

1 回答 1

1

Well there's no handy solution in backbone form scratch, cause nesting views is not handeled there is any way. What i can advise you is to set the parental relation(so each view knows it's parent) rather then parent knows all of it's subviews, and as long as view is an event emitter by default toy can do something like this [pseudo-code]:

parent view:

 var BaseView = Backbone.View.extend({

  keydown: function(e){
    this.trigger("custom.keydown");
    return this;
  },

});

child view:

var ChildView = Backbone.View.extend({

  initialize:function(){
       this.parent.on("custom.keydown",this.keydown,this);
  }

});
于 2013-05-11T12:14:29.580 回答