最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone.js accessing another view function - Stack Overflow

programmeradmin0浏览0评论

I'm developing an application with Backbone.js

I have 2 view and I want use a function defined in other view:

var FormView = Backbone.View.extend({
  initialize: function(){
    resultsView.myFunction();
  }

})


var resultsView = Backbone.View.extend({
  myFunction: function(){
    alert('test')
  }
})

How I can do it?

I'm developing an application with Backbone.js

I have 2 view and I want use a function defined in other view:

var FormView = Backbone.View.extend({
  initialize: function(){
    resultsView.myFunction();
  }

})


var resultsView = Backbone.View.extend({
  myFunction: function(){
    alert('test')
  }
})

How I can do it?

Share Improve this question edited May 5, 2015 at 14:28 Arslan Ali 17.8k9 gold badges63 silver badges83 bronze badges asked Feb 25, 2013 at 17:20 ValerianeValeriane 9543 gold badges17 silver badges39 bronze badges 1
  • In general, You don't want to do that. You'll end up with spaghetti code. If it's a general function, abstract it out. If the function really does have to do with something that resultsView should be concerned with, then listen for changes in the model or trigger an event on formView that resultsView listens to. – steveax Commented Feb 25, 2013 at 17:35
Add a ment  | 

3 Answers 3

Reset to default 5

You're doing it the opposite way. You can do a base view that other views can extend and implement such as:

/** Any Views that inherit from this View can use the myFunction() */
var BaseView = Backbone.View ({
  myFunction : function(param) {
      alert(param);
  }
});

/** Inherit from the base view above */
var ChildView = BaseView.extend({
  initialize : function(){
      this.myFunction('test');
  }
});

var instanceView = new ChildView({});

why not use events?

routing-and-the-event-aggregator-coordinating

When you use Backbone.View.extend, you are creating a class. In order to use the class, you need to create an instance using the new operator. It's conventional to start class names with a Capital letter, and instance variable names with a small letter, so I'll use that naming convention in the following samples:

//declare view class
var ResultsView = Backbone.View.extend({
  myFunction: function(){
    alert('test')
  }
});

Create an instance of the class, and pass it into your FormView:

var resultsView = new ResultsView();
var formView = new FormView({ resultsView: resultsView });

Access the passed argument in the FormView.initialize:

var FormView = Backbone.View.extend({
  initialize: function(options){
    options.resultsView.myFunction();
  }
});
发布评论

评论列表(0)

  1. 暂无评论