Backbone里两个view(或者说collection)怎么交互?


我有viewA、viewB,分别对应collectionA、collectionB(他们model类型相同)
目标:点击viewA中一个元素时,将这个元素对应的model添加到collectionB,viewB同上所述
我该怎么做?


 var ViewA = Backbone.ViewA.extend({
  el: $('xxx'),
  .....
  events: {
   "click": "trans"
  },
  trans: function(event) {
    var index = event.target.dataset.n;//通过data、元素index之类乱七八糟的获取序列号,总之不重要
    //我疑惑的是下面的
    var model = this.collection.at(index);
    collectionB.add(model) //这样也太傻了吧
  }
});
var viewA = new ViewA({collection: collectionA})

感觉别别扭扭,依赖乱七八糟的

JavaScript backbone.js

姆了个Q~ 11 years, 1 month ago

楼主的意思比较清楚,而且感觉是对的,乱乱的,其实是因为这样写会 太耦合 ,ViewA不应该包含ViewB

而最好通过事件进行交互。

如:


 var eventAcrossView = _.extend({}, Backbone.Events);

// view one needs to trigger an event in view2
ViewA = Backbone.View.extend({

    trans: function(event) {
        eventAcrossView.trigger('viewAClicked', { 'some' : 'data' } );
    })
})

ViewB = Backbone.View.extend({
    initialize: function() {
        eventAcrossView.on('viewAClicked', this.onViewAClicked, this);
    },
    onViewAClicked : function() {
        // update model
    }
})

YuanL answered 11 years, 1 month ago

Your Answer