Backbone passing view contexts
by bowheart
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<div id="body"><input id="input" /></div>
JavaScript
document.View1 = Backbone.View.extend({
initialize: function() {
this.name = "Hello";
},
func: function() {
var view = this;
var cond = {
context: view,
message: "Fail",
fields: ["input"],
condition: function() {
return $('#' + this.fields[0]).val() !== "";
},
otherFunc: 'otherFunc'
};
new document.View2(cond);
},
func2: function() {
console.log('called from in town!');
},
otherFunc: function() {
console.log('called from out of town!');
this.func2();
}
});
document.View2 = Backbone.View.extend({
initialize: function(cond) {
var view = this;
view.cond = cond;
if (!view.cond.condition()) view.cond.context[view.cond.otherFunc]();
}
});
var view1 = new document.View1();
view1.func();