Backbone.js - Binding from one view to another?

懵懂的女人 提交于 2019-12-21 15:40:30

问题


I have a main app view, with a filter menu in the header. When it's clicked, I want to filter content in a seperate news-feed view. But I don't know how to bind events (and pass class data) from clicks in one view to a function in another.

How can I accomplish this?


回答1:


There are a number of ways to accomplish this, but probably you want to create a model object, which is shared between the two views. Then on 'click' in view one, update the model object, and bind 'on change' in view two to the model object.

Basically, you can set up both views to stay in sync with the model object, and any changes to the object will result in changes to the view.




回答2:


Everything in Backbone inherits from Backbone.Events, so you can trigger and bind events from anywhere (docs for Backbone.Events):

var View1 = Backbone.View.extend();

var View2 = Backbone.View.extend({
    eventHandler: function(data) {alert(data)}
});

var v1 = new View1;
var v2 = new View2;

v1.bind('hello-world-event', v2.eventHandler)
v1.trigger('hello-world-event', 'Hello World!')

Note that in this example, when v2.eventHandler is called, 'this' will refer to v1. See the backbone docs for more.



来源:https://stackoverflow.com/questions/6930621/backbone-js-binding-from-one-view-to-another

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