Backbone: How to trigger methods in a parent view

南楼画角 提交于 2020-01-04 04:22:27

问题


I have an alphabet filter view (a, b, c, d etc) that a lot of views will be using. I have setup a method on the main view to fetch results from the API using the letter clicked.

I've setup this by passing a callback function down to the alphabet filter as per below:

view = new App.Views.Common.AlphabetFiltersIndexView(filterCallback: @paginationFilter)
@$(".pagination-vertical").replaceWith(view.render().el)

Calling the filterCallback and passing arguments works, however the paginationFilter method called now belongs to the Alphabet Filters.

Question: How do I call a parent view's method and keep the method's relationship with the original top view?


回答1:


You could go about this two ways:

  1. Pass the parent view to your child view, OR have your child view find its parent via a global object, if you're using one. Call the parent view's function from the child

  2. You could have your child view raise an event when you need the parent view's function to be called. Your parent view should be listening for this event from your child view, and respond by calling the method required.




回答2:


You should trigger an event in the child view using something like

this.trigger('event', [args]);

and listen to it from the parent view

this.listenTo(childView, 'event', this.paginationFilter);

(Recommend giving the event a proper name. Consider a name such as 'page:change'. 'page' is a sort of namespace just to make the events in large application easier to name and organize. There is no real namespace functionality.)




回答3:


You can use the following Underscore call in your AlphabetFiltersIndexView in it'sinitialize method

_.bindAll(callBackContext, "YourCallBack");

This will ensure the callback is bound to the object of your choice (The parent view).

You can pass in the values of callBackContext and "YourCallBack" as parameters to the AlphabetFiltersIndexView, which you can then control based on the context of the parent view.



来源:https://stackoverflow.com/questions/16931120/backbone-how-to-trigger-methods-in-a-parent-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!