简体   繁体   中英

How listen to other model events from your model in backbone js?

I have a problem with backbone. I have two models: A and B

I need to listen to events in one model (for instance A), and then after the event has happened make changes in the view of model B and its view.

Does anyone have a fairly simple example how such functionality can be implemented in backbone?

var Model_A_View= Backbone.View.extend({


 events: {
   // some events;
     "click" : "ok",
  },

   initialize: function () {

    this.Model_A = new Model_A({ // });
  }

   var Model_B_View= Backbone.View.extend({


 events: {
   // some events;
  },


   initialize: function () {

    this.Model_B = new Model_B({ // });
    this.listenTo( model_A , "change: ok", this.dosomethingFunction());

  }
   dosomethingFunction: function () {
     //dosomething
  }

Your code hard to read, no code style , and some synax error.

However, you'd better create model outside of you view's initialize function, and pass the model as a para when new a view:

var modelA = new Model_A();
var viewA = new Model_A_View({
  model: modelA
});

var modelB = new Model_B();
var viewB = new Model_B_View({
  model: modelB
});

viewB.listenTo(modelA, "change:ok", viewB.dosomethingFunction);

As variant you can use The Backbone Events . Few simple steps, how you can do this.

1.Specify events global object:

window._vent = _.extend({}, Backbone.Events);

2.Specify event triggers in your view/model/collection. For example for your view:

var Model_A_View = Backbone.View.extend({
    events: {
       // some events;
       "click" : "ok",
    },
    initialize: function() {
        this.Model_A = new Model_A({});
    },
    ok: function() {
        vent.trigger('model_A:update', this.model); //you can also send your model   
    }
});

3.Specify event listening in your Model_B :

var Model_B_View = Backbone.View.extend({
    initialize: function() {
        this.Model_B = new Model_B({});
        vent.on('model_A:update', this.updateModel, this);
    },
    updateModel: function() {
        //this function will be call after `model_A:update` event triggered
        //do something with Model_B
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM