admin管理员组

文章数量:1326344

How do I make it so that a function runs every time a backbone.js view is initialized?

I'm looking for something that I can put on outside of my normal view code, as an extension to backbone.js.

The idea is to reduce the amount of boilerplate.

How do I make it so that a function runs every time a backbone.js view is initialized?

I'm looking for something that I can put on outside of my normal view code, as an extension to backbone.js.

The idea is to reduce the amount of boilerplate.

Share Improve this question edited Apr 7, 2022 at 18:22 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 24, 2011 at 22:45 HarryHarry 55k76 gold badges186 silver badges270 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Since Javascript is not a true object oriented programing language, you can't use inheritance to solve your problem as you could if it was java or c#.

One possible solution is to use the factory design pattern.

Instead of instantiating your view directly, you can call a factory method that will instantiate your view.

var viewFactory = function(view, viewOptions) {
  //perform your boilerplate code
  return new view(viewOptions);
}

AView = Backbone.View.extend({});

var person = new Backbone.Model({name: 'Paul'});
var view = viewFactory(AView, { model: person });

Here's a jsfiddle example

It's not as an elegant solution that is possible with other languages, but it does the job.

use the builtin backbone.js initialize function:

http://documentcloud.github./backbone/#View-constructor

var ItemView = Backbone.View.extend({
  initialize: function(){
    alert('View Initialized');
  }
});

EDIT: I should be more clear.

In the words of Patrick Ewing found here http://podcast.rubyonrails/programs/1/episodes/railsconf-2007:

"if it walks like a duck and talks like a duck, it’s a duck, right? So if this duck is not giving you the noise that you want, you’ve got to just punch that duck until it returns what you expect"

Duck Punch (or Monkey Patch if you prefer) the Backbone object.

Backbone.View.prototype.initialize = function(){
  alert('I overrode the default initialize function!');
}

You can use Backbone.Events.

On the top level of your app or on the global object:

app.eventManager = {};
_.extend(app.eventManager, Backbone.Events);
app.eventManager.bind("newView", app.yourfunction(view));

And in the initialize method of any view you want to trigger your function:

app.eventManager.trigger("newView", this);

where "this" is the view instance passed as the "view" parameter to your function.

本文标签: javascriptWhen initializing a backbone viewStack Overflow