I have created a new backbone.js widget model which I hope to extend:
var Widget = Backbone.Model.extend({
constructor: function() {
console.log('Widget constructor called.');
}
});
Depending on the page a user views a number of widgets will be loaded via Ajax, so for each widget I will do something like this:
$.getScript('widgets/widget1', function(xhr){
var widget1 = new pieChartWidget();
widget1.render();
widget1.update();
});
Contents of "widgets/widget1":
$(function() {
var pieChartWidget = Widget.extend({
render: function(json) {
console.log('Widget render called.');
},
update: function(json) {
console.log('Widget update called.');
}
});
});
In my Firebug console I get "pieChartWidget is not defined". I know the Javascript is being loaded successfully, I just cannot extend the "Widget" model from it.
Your widget is defined within a function. So all variable declared there are only visible withing then functions scope.
$(function() {
var pieChartWidget;
// pieChartWidget is only visible here!
});
// pieChartWidget not visible here!
To have access to the widget from outside of the function you have to assign it to a global variable (eg. your applications namespace). You could also use window (not the preferred way).
Your code should work unchanged if you assign your widget to window like so:
$(function() {
window.pieChartWidget = Widget.extend({
render: function(json) {
console.log('Widget render called.');
},
update: function(json) {
console.log('Widget update called.');
}
});
});