3

How can I call a method of View#1 from view#2 in backbone?

view#1 = Backbone.View.extend({
    plot_markers:function(){
        /*some code */
    } 
});

view#1 = Backbone.View.extend({
    initialize:function(){
        view#1.plot_markers();
    }
});

How do i set global methods in backbone. where many view can use the same method

Thanking you

Joel James
  • 3,870
  • 9
  • 32
  • 47
  • 1
    possible duplicate of [access function in one view from another in backbone.js](http://stackoverflow.com/questions/7708195/access-function-in-one-view-from-another-in-backbone-js) – Edward M Smith Sep 06 '12 at 19:23

4 Answers4

1

View#2 would have to have a reference to View#1, but that can be dangerous as it would be easy to create a circular reference. A better way of approaching this would be to have an intermediary, such as a controller do the method invocation. View#1 would trigger an event that the controller listens to, and in turn invoke the proper method on View#2 or vice-versa. The idea is to keep your views ignorant of each other, as this follows the whole idea of "separation of concerns."

Brendan Delumpa
  • 1,155
  • 1
  • 6
  • 11
0

You could have View2 extend View1

class View1 extends Backbone.View
  plot_markers: -> # dot stuff 

class View2 extends View1
  initialize: ->
     @plot_markers()
Running Turtle
  • 12,360
  • 20
  • 55
  • 73
0

try this,

view1 = Backbone.View.extend({

    plot_markers:function(){
        //add your code here,..
        alert('called....'); 
    } 
});

view2 = Backbone.View.extend({
    initialize:function(){
        var v1 = new view1();
        v1.plot_markers();
    }
});
var v2 = new view2();
Array out of bound
  • 1,133
  • 7
  • 24
0

Depending on how your application is structured and how views relate to each other you can either 1) fire an event your router listens to and executes another action in response (like Brendan Delumpa suggested), or 2) create a global event aggregator that you can listen to anywhere and trigger events on anywhere.

Derick Bailey has written on how and when to use event aggregators in Backbone. Here's a simple example:

App = {};
App.events = _.extend({}, Backbone.Events);

// Subscribe to your:event
App.events.on("your:event", function(){
  // Carry out whatever's supposed to happen when the event
  // has been triggered here.
});

// Publish your:event
App.events.trigger("your:event");
Patrick Berkeley
  • 2,206
  • 21
  • 26