Backbone.js with $.getScript Extending Model - javascript

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.');
}
});
});

Related

Backbone JS Button to open a new view, save values in form

Im new to backbone and I'm looking to a very simple 2 view configuration page usig backbone.
I have the following code;
define(
["backbone","...","..."],
function(Backbone, ... , ... ) {
var PopupView = Backbone.View.extend({
initialize: function initialize() {
Backbone.View.prototype.initialize.apply(this,arguments);
},
events: {
"click .save_conf_button": "save_conf",
},
render: function() {
this.el.innerHTML = this.get_popup_template();
return this;
},
save:conf: function save_conf() {
//get the field values from popup_template
//var items = jquery(....);
});
var ExampleView = Backbone.View.extend({
//Starting view
initialize: function initialize() {
Backbone.View.prototype.initialize.apply(this, arguments);
},
events: {
"click .setup_button": "trigger_setup", //Triggers final setup
"click .create_conf_button": "trigger_popup_setup", //This is the conf popup
},
render: function() {
this.el.innerHTML = this.get_start_html();
return this;
},
trigger_popup_setup: function trigger_popup_setup() {
console.log("Pop up");
//this.el.innerHTML = this.get_popup_template();
PopupView.render();
...
},
}); //End of exampleView
return ExampleView;
} // end of require asynch
); // end of require
E.g. The ExampleView is the starting view with a couple of fields and 2 buttons; create popup and save. Upon pressing the create_conf_button I want to render the popup view, however this does not seem to work as I expected. (Uncaught TypeError: PopupView.render is not a function)
I'm not sure how to proceed and additionally what the "best practice" is for generating these types of dialogs?
Additionally, keeping the values filled in on the previous page after returning from the popupview would be preferential.
Thanks for any help
try
new PopupView.render()
you have to create an instance to call the methods this way
#ashish is correct, you have to instantiate an instance of the PopupView before calling its render method. Currently, you have defined a blueprint for a view called PopupView, which will act as a constructor for newly created PopupView view instances. In order to use this defined view I would suggest storing it in ExampleView's render or initialize method:
// Example View's initialize method
initialize: function initialize() {
this.popUpView = new PopupView();
Backbone.View.prototype.initialize.apply(this, arguments);
},
then referencing it in your trigger_popup_setup function as follows:
trigger_popup_setup: function trigger_popup_setup() {
console.log("Pop up");
//this.el.innerHTML = this.get_popup_template();
this.popUpView.render();
...
},
As for storing state Backbone models are used for that :)
In general to nest subviews within a master view in Backbone you can do the following:
initialize : function () {
//...
},
render : function () {
this.$el.empty();
this.innerView1 = new Subview({options});
this.innerView2 = new Subview({options});
this.$('.inner-view-container')
.append(this.innerView1.el)
.append(this.innerView2.el);
}
In this example the master view is creating instances of it's subviews within its render method and attaching them to a corresponding DOM element.

this.$el.off is not a function

Previously this will work but I've update the underscore and backbone to the latest version, then I got error of
Uncaught TypeError: this.$el.off is not a function
http://jsfiddle.net/mmm770v8/
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var template = _.template( $("#search_template").html(), {} );
this.el.html( template );
},
events: {
"click input[type=button]": "doSearch"
},
doSearch: function(){
// Button clicked
console.log(this.el.find('#search_input').val());
}
});
You have several problems:
Your fiddle was using jQuery 1.5.2 which is ancient and used bind/unbind instead of on/off. Backbone expects a more recent version of jQuery which has on and off functions.
You're using this.el where you mean this.$el. this.el is just a plain old DOM node, this.$el is the cached $(this.el).
The var html = _.template(tmpl, data) form of _.template went away in Underscore 1.7.0. You now need a two step process:
var t = _.template(tmpl);
var h = t(data);
so your render should look more like this:
render: function() {
var template = _.template($("#search_template").html());
this.$el.html(template({}));
}
Updated fiddle: http://jsfiddle.net/ambiguous/L5z4agh4/

backbone.js removing template from DOM upon success

I'm writing a simple message board app to learn backbone. It's going ok (a lot of the use of this isn't making sense) but am a little stuck in terms of how I would remove a form / html from the dom. I have included most of the code but you can see about 4 lines up from the bottom, the part that isn't working. How would I remove this from the DOM?
thx in advance
var MbForm=Backbone.View.extend({
events: {
'click button.add-new-post': 'savePost'
},
el: $('#detail'),
template:_.template($('#post-add-edit-tmpl').html()),
render: function(){
var compiled_template = this.template();
this.$el.html(compiled_template);
return this;
},
savePost: function(e){
//var self=this;
//console.log("I want you to say Hello!");
data={
header: $('#post_header').val(),
detail: $('#post_detail').val(),
forum_id: $('#forum_id').val(),
post_id: $('#post_id').val(),
parent_id: $('#parent_id').val()
};
this.model.save(data, {
success: function(){
alert('this saved');
//$(this.el).html('this is what i want');
this.$el.remove();// <- this is the part that isn't working
/* none of these worked - error Uncaught TypeError: Cannot call method 'unbind' of undefined
this.$el.unbind();
this.$el.empty();
this.el.unbind();
this.el.empty();
*/
//this.unbind();
//self.append('this is appended');
}
});
Backbone doesn't call the success callback with any particular this, it is simply called as a plain function. So, this inside your success callback will be window rather than the view you're expecting it to be.
Any of the usual solutions will work:
Save the desired this in a local variable:
var _this = this;
this.model.save(data, {
success: function() {
//...
_this.remove();
Use a bound function:
this.model.save(data, {
success: _(function() {
//...
this.remove();
}).bind(this)
Use a named bound function:
initialize: function() {
_.bindAll(this, 'save_success');
}
//...
this.model.save(data, {
success: this.save_success
And the usual variations on the above.
Also note that I switched to View#remove since you are apparently trying to remove the whole view and that's the usual way to do it.

Backbone.js: How do you call a View's "method" from outside the View's scope (e.g: inside a model's validation handler)

Basically, I'm trying to do something like this:
Person = Backbone.Model.extend({
validate: { ... },
initialize: function(){
this.bind('error', ?......?); <== what do I put?
},
// I DON'T WANT TO CALL THIS ONE
handleError: function(){ }
});
ViewOne = Backbone.View.extend({
//I WANT TO CALL THIS ONE:
handleError: function(model, error){
//display inside segmented view using jQuery
};
});
I tried options.view.handleError but it doesn't work...
My main purpose: I want a specific View that created the model to handle the error, not have the model to globally handle it all. For example, I want View#1 to do an alert while I want View#2 to display in a div. I don't know if this is the right way of doing it. If not, I would be gladly accept your help.
Thank you.
UPDATE: here's my jsFiddle
http://jsfiddle.net/jancarlo000/87mAk/
Since Backbone 0.5.2 it is recommended to drop bindAll in favor of third argument to bind if you need to pass the context.
ViewOne = Backbone.View.extend({
initialize: function() {
this.model.on('error', this.handleError, this);
},
handleError: function(model, error) { /* ... */ }
});
...
var person = new Person();
var viewone = new ViewOne({model : person});
General note here is that Models should never know about their Views. Only Views should subscribe to Model events.
You have it backwards, the view should be binding to the model's events:
ViewOne = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'handleError');
this.model.bind('error', this.handleError);
},
handleError: function(model, error) { /* ... */ }
});

backbone.js model not firing events

I have a view which doesn't seem to want to render as the model's change event is not firing.
here's my model:
var LanguagePanelModel = Backbone.Model.extend({
name: "langpanel",
url: "/setlocale",
initialize: function(){
console.log("langselect initing")
}
})
here's my view:
var LanguagePanelView = Backbone.View.extend({
tagName: "div",
className: "langselect",
render: function(){
this.el.innerHTML = this.model.get("content");
console.log("render",this.model.get(0))
return this;
},
initialize : function(options) {
console.log("initializing",this.model)
_.bindAll(this, "render");
this.model.bind('change', this.render);
this.model.fetch(this.model.url);
}
});
here's how I instantiate them:
if(some stuff here)
{
lsm = new LanguagePanelModel();
lsv = new LanguagePanelView({model:lsm});
}
I get logs for the init but not for the render of the view?
Any ideas?
I guess it's about setting the attributes of the model - name is not a standard attribute and the way you've defined it, it seems to be accessible directly by using model.name and backbone doesn't allow that AFAIK. Here are the changes that work :) You can see the associated fiddle with it too :)
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
//adding custom attributes to defaults (with default values)
defaults: {
name: "langpanel",
content: "Some test content" //just 'cause there wasn't anything to fetch from the server
},
url: "/setlocale",
initialize: function(){
console.log("langselect initing"); //does get logged
}
});
var LanguagePanelView = Backbone.View.extend({
el: $('#somediv'), //added here directly so that content can be seen in the actual div
initialize : function(options) {
console.log("initializing",this.model);
_.bindAll(this, "render");
this.render(); //calling directly since 'change' won't be triggered
this.model.bind('change', this.render);
//this.model.fetch(this.model.url);
},
render: function(){
var c = this.model.get("content");
alert(c);
$(this.el).html(c); //for UI visibility
console.log("render",this.model.get(0)); //does get logged :)
return this;
}
});
var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});
}); //end ready
UPDATE:
You don't need to manually trigger the change event - think of it as bad practice. Here's what the backbone documentation says (note: fetch also triggers change!)
Fetch
model.fetch([options])
Resets the model's state from the server.
Useful if the model has never been populated with data, or if you'd
like to ensure that you have the latest server state. A "change" event
will be triggered if the server's state differs from the current
attributes. Accepts success and error callbacks in the options hash,
which are passed (model, response) as arguments.
So, if the value fetched from the server is different from the defaults the change event will be fired so you needn't do it yourself. If you really wish to have such an event then you can use the trigger approach but custom name it since it's specific to your application. You are basically trying to overload the event so to speak. Totally fine, but just a thought.
Change
model.change()
Manually trigger the "change" event. If you've been
passing {silent: true} to the set function in order to aggregate rapid
changes to a model, you'll want to call model.change() when you're all
finished.
The change event is to be manually triggered only if you've been suppressing the event by passing silent:true as an argument to the set method of the model.
You may also want to look at 'has changed' and other events from the backbone doc.
EDIT Forgot to add the updated fiddle for the above example - you can see that the alert box pops up twice when the model is changed by explicitly calling set - the same would happen on fetching too. And hence the comment on the fact that you "may not" need to trigger 'change' manually as you are doing :)
The issue was resolved my adding
var LanguagePanelModel = Backbone.Model.extend({
//adding custom attributes to defaults (with default values)
defaults: {
name: "langpanel",
content: "no content",
rawdata: "no data"
},
events:{
//"refresh" : "parse"
},
url: "/setlocale",
initialize: function(){
log("langselect initing");
//this.fetch()
},
parse: function(response) {
this.rawdata = response;
// ... do some stuff
this.trigger('change',this) //<-- this is what was necessary
}
})
You don't need attributes to be predefined unlike PhD suggested. You need to pass the context to 'bind' - this.model.bind('change', this.render, this);
See working fiddle at http://jsfiddle.net/7LzTt/ or code below:
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
url: "/setlocale",
initialize: function(){
console.log("langselect initing");
}
});
var LanguagePanelView = Backbone.View.extend({
el: $('#somediv'),
initialize : function(options) {
console.log("initializing",this.model);
// _.bindAll(this, "render");
//this.render();
this.model.bind('change', this.render, this);
//this.model.fetch(this.model.url);
},
render: function(){
var c = this.model.get("content");
alert(c);
$(this.el).html(c);
console.log("render",this.model.get(0));
return this;
}
});
var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});
lpm.set({content:"hello"});
}); //end ready

Categories