Reputation: 63727
A Backbone Collection and some Views are created in the return function of click()
as shown in the code snippet below.
Problem: How can I access backbone.js objects like the Collection productList
using the Javascript console? this.productList
does not return anything, so I believe productList
is not a direct child of the window
object. How then should I create productList
collection?
JS Code
$('#submit_btn').click(function() {
console.log('do something');
}, function() {
this.productList = new ProductCollection();
var self = this;
self.productListView = new ProductListView({ collection: self.productList });
this.productList.fetch({
data: {gender: 'men'},
processData: true
});
});
});
Upvotes: 2
Views: 4349
Reputation: 22768
You could attach productList to the window
object.
$('#submit_btn').click(function() {
console.log('do something');
}, function() {
window.productList = new ProductCollection();
var self = this;
self.productListView = new ProductListView({ collection: self.productList });
window.productList.fetch({
data: {gender: 'men'},
processData: true
});
});
});
But you'd be better off refactoring your code like @avk said so submit_btn
was part of a Backbone view.
Regardless of what's going on, since this
in that instance refers to the closure in which your code is running, it's not going to be accessible until you export it to an externally available object.
Upvotes: 0
Reputation: 1004
Right now in this case you cannot can everything is in an anonymous function so you cant access it after the function has executed. This is anyways not the right way to do things, or not the backbone way.
This is how i generally do stuff, create a central namespace like app and then create all the models, collections and views to that namespace as
window.App = {
//model
Curve : {},
//collection
CurveManager : {},
//view
Views : {},
//controller
Controller : {}
}
plus i think that you should take care of the click event from a backbone view itself then it would be comparatively easier for you to visualize things. For example in http://backbonejs.org/docs/todos.html take a look at the AppView events. that should make things much more clearer.
here is that part of the code
var AppView = Backbone.View.extend({
el: $("#todoapp"),
statsTemplate: _.template($('#stats-template').html()),
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},
.
. // more code in between
.
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return;
Todos.create({title: this.input.val()});
this.input.val('');
},
I generally look at other peoples code on github and try to learn how they do things and how things should be done, i suggest you do the same. It helps a lot :) The todoapp annotated source is really clean and pretty easy to understand.
Upvotes: 2